Pandas Dataframe:按列名绘制颜色 [英] Pandas Dataframe: plot colors by column name

查看:203
本文介绍了Pandas Dataframe:按列名绘制颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用几行绘制一个 Pandas DataFrame,每行都有特定的颜色(由 rgb 值指定).我正在寻找一种方法,通过将绘图线颜色直接分配给 DataFrame 列名称而不是按顺序列出它们,从而使我的代码更具可读性.

I'm plotting a Pandas DataFrame with a few lines, each in a specific color (specified by rgb value). I'm looking for a way to make my code more readable by assigning the plot line colors directly to DataFrame column names instead of listing them in sequence.

我知道我可以做到:

import pandas as pd

df = pd.DataFrame(columns=['red zero line', 'blue one line'], data=[[0, 1], [0, 1]])
df.plot(colors = ['#BB0000', '#0000BB']) # red and blue

但是有很多不止两行,我真的希望能够通过列标题指定颜色,以使代码易于维护.比如这个:

but with a lot more than two lines, I'd really like to be able to specify the colors by column header, to make the code easy to maintain. Such as this:

df.plot(colors = {'red zero line': '#FF0000', 'blue one line': '#0000FF'})

colors 关键字实际上不能是字典.(从技术上讲,它被类型转换为列表,从而生成一个列标签列表.)

The colors keyword can't actually be a dictionary though. (Technically it's type-converted to list, which yields a list of the column labels.)

我知道 pd.DataFrame.plot 继承自 matplotlib.pyplot.plot 但我找不到 colors 的文档关键词.这两种方法的文档都没有列出这样的关键字.

I understand that pd.DataFrame.plot inherits from matplotlib.pyplot.plot but I can't find the documentation for the colors keyword. Neither of the documentations for the two methods lists such a keyword.

推荐答案

如果您创建一个将列名映射到颜色的字典,您可以使用列表推导式动态构建颜色列表,您只需 get 列名的颜色.这也允许您指定默认颜色,以防您错过一列.

If you create a dictionary mapping the column names to colors, you can build the color list on the fly using a list comprehension where you just get the color from the column name. This also allows you to specify a default color in case you missed a column.

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame([[0, 1, 2], [0, 1, 2]], 
                  columns=['red zero line', 'blue one line', 'extra'])

color_dict = {'red zero line': '#FF0000', 'blue one line': '#0000FF'}

# use get to specify dark gray as the default color.
df.plot(color=[color_dict.get(x, '#333333') for x in df.columns])
plt.show()

这篇关于Pandas Dataframe:按列名绘制颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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