我试图在熊猫中绘制一些数据,并且内置的绘图功能可以方便地绘制每列一行.我想要做的是根据我制作的分类手动为每一行分配颜色.
以下作品:
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)
Run Code Online (Sandbox Code Playgroud)
但是当我的索引是整数时它不再起作用并抛出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)
Run Code Online (Sandbox Code Playgroud)
我理解它的方式是,当使用整数索引时,它必须从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)
Run Code Online (Sandbox Code Playgroud)
我的问题是:
编辑:
我意识到即使在第一种情况下,代码也没有按照我的预期去做.似乎pandas仅匹配DataFrame和Series的索引,如果两者都是从0开始的整数索引.如果不是这种情况,则抛出KeyError或者如果索引是str,则使用元素的顺序.
它是否正确?有没有办法匹配Series和DataFrame索引?或者我必须确保以正确的顺序传递颜色列表?
Myk*_*tko 12
要设置每条线的颜色,您可以使用参数style
。例如:
df = pd.DataFrame({'A': [1, 2, 4], 'B': [1, 3, 9]})
df.plot(style={'A': 'r', 'B': 'g'})
Run Code Online (Sandbox Code Playgroud)
使用marker|line|color形式的快捷字符串表示法,您还可以设置标记和线类型:
df = pd.DataFrame({'A': [1, 2, 4], 'B': [1, 3, 9]})
df.plot(style={'A': '*:r', 'B': '+--g'})
Run Code Online (Sandbox Code Playgroud)
the*_*cus 10
这里发生了什么?
关键字参数颜色是从中继承的 matplotlib.pyplot.plot().文档中的详细信息并未明确表示您可以在绘图时输入颜色列表.鉴于颜色是来自matplotlib的关键字参数,我建议不要使用Pandas系列来保存颜色值.
我怎样才能做到这一点?
使用列表而不是系列.如果您使用的索引系列旨在将DataFrame的列与特定颜色相匹配,则需要先对系列进行排序.如果列不按顺序排列,则需要对列排序.
# 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
Run Code Online (Sandbox Code Playgroud)
尝试:
df.plot(color = s.values)
Run Code Online (Sandbox Code Playgroud)
无论索引的比例如何,这都会分配颜色。
编辑:
我尝试了三列:
df = pd.DataFrame({'1': [1, 2, 3, 4], '2': [1, 2, 1, 2], '3': [4, 3, 2, 1]})
s = pd.Series(['c','y','r'], index=[1,3,2])
df.plot(color = s.sort_index().values)
Run Code Online (Sandbox Code Playgroud)
并对它有效的系列进行排序。