【问题标题】:df.plot.scatter: c and cmapdf.plot.scatter: c 和 cmap
【发布时间】:2021-10-03 05:46:21
【问题描述】:

我有一个数据框(nb - 数据是虚拟数据,不代表图中的内容):

    Index     BGC frequency - Count     Proportion of total BGCs both captured and not captured by antiSMASH - %
  species_a            1                                       2
  species_b            3                                       4
     ...              ...                                     ...

我想制作BGC frequency - CountProportion of total BGCs both captured and not captured by antiSMASH - % 的散点图,点根据分类Index 和图例着色。

import matplotlib.pyplot as plt
from matplotlib import colors
import pandas as pd

colorlist = list(colors.ColorConverter.colors.keys())
captured_df.plot.scatter(x='BGC frequency - Count', 
                         y= 'Proportion of total BGCs both captured and not captured by antiSMASH - %' , 
                          c = colorlist,
                         title = 'BGCs with an antiSMASH region')

让我靠近:

但我无法获得传奇。理想情况下,我想要类似于here,第 69 行所示的内容:

但是当我尝试时:

df.plot.scatter(x='BGC frequency - Count', y='Proportion of total BGCs both captured and not captured by antiSMASH - %', c=df.index, cmap="viridis", s=50)

我明白了:

ValueError: 'c' argument must be a mpl color, a sequence of mpl colors or a sequence of numbers, not Index(...list of index species names...)

我不确定这是为什么 - 我认为 cmapc 数据转换为正确数据类型的列表?上面的链接明确处理分类数据 -

如果将分类列传递给 c,则离散颜色条将 生产出来

另外请注意我不想要一个数字颜色条 - this 不会有太大用处:

感谢阅读:D

【问题讨论】:

    标签: python pandas colors scatter


    【解决方案1】:

    诀窍是将“类型”列转换为分类(在您的情况下为 Index 列)。

    例如:

    d = pd.DataFrame([["a", 1,3], ["b", 3,3], ["b", 2,3], ["a", 5,2]], columns=['type', 'x', 'y'])
    d['type'] = pd.Categorical(d['type'])
    d.plot.scatter(x='x', y='y', c='type', cmap='inferno')
    plt.show()
    

    这应该可行。

    另外值得一提的是,这个功能来自Pandas 1.3.0版 (July 2. 2021)!

    确保您使用适当的版本。

    【讨论】:

      猜你喜欢
      • 2020-05-07
      • 2019-02-06
      • 2012-09-19
      • 1970-01-01
      • 2012-03-25
      • 1970-01-01
      • 2021-06-02
      • 2019-12-12
      • 1970-01-01
      相关资源
      最近更新 更多