在 pandas 中分配线条颜色 [英] Assign line colors in pandas

查看:88
本文介绍了在 pandas 中分配线条颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在熊猫中绘制一些数据,并且内置的绘图功能可以方便地在每列中绘制一行.我要做的是根据我进行的分类为每行手动分配一种颜色.

以下作品:

df = pd.DataFrame({'1': [1, 2, 3, 4], '2': [1, 2, 1, 2]})
s = pd.Series(['c','y'], index=['1','2'])
df.plot(color = s)

但是当我的索引是整数时,它将不再起作用并抛出KeyError错误:

df = pd.DataFrame({1: [1, 2, 3, 4], 2: [1, 2, 1, 2]})
s = pd.Series(['c','y'], index=[1,2])
df.plot(color = s)

我的理解是,使用整数索引时,它必须以某种方式从0开始.这是我的猜测,因为以下内容也可以工作:

df = pd.DataFrame({0: [1, 2, 3, 4], 1: [1, 2, 1, 2]})
s = pd.Series(['c','y'], index=[1,0])
df.plot(color = s)

我的问题是:

  • 这是怎么回事?
  • 假设我有一个不是从0开始或不是由连续数字组成的整数索引,那么我如何进行这项工作而不必将索引转换为从0开始的字符串或重新索引?

我意识到,即使在第一种情况下,代码也无法实现我期望的功能. 似乎pandas仅在两者都是从0开始的整数索引时才匹配DataFrame和Series的索引.如果不是这种情况,则会引发KeyError,或者如果索引是str,则使用元素的顺序.

这是正确的吗?有没有办法匹配Series和DataFrame索引?还是我必须确保以正确的顺序传递颜色列表?

解决方案

这是怎么回事?

关键字参数颜色继承自 matplotlib.pyplot.plot().文档中的详细信息并未明确指出在打印时可以放入颜色列表.鉴于color是matplotlib的关键字参数,我建议不要使用Pandas系列保存颜色值.

我该如何进行这项工作?

使用列表而不是系列.如果您使用的系列的索引旨在使DataFrame的列与特定颜色匹配,则需要首先对系列进行排序.如果列不按顺序排列,则需要 解决方案

What is happening here?

The keyword argument color is inherited from matplotlib.pyplot.plot(). The details in the documentation don't make it clear that you can put in a list of colors when plotting. Given that color is a keyword argument from matplotlib, I'd recommend not using a Pandas Series to hold the color values.

How can I make this work?

Use a list instead of a Series. If you were using a Series with an index meant to match the columns of your DataFrame to specific colors, you will need to sort the Series first. If the columns are not in order, you will need to sort the columns as well.

# Option 1
s = s.sort_index()
df.plot(color = s.values) # as per Fiabetto's answer

# Option 2
df.plot(color = ['c', 'y']) # other method

这篇关于在 pandas 中分配线条颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆