gpt4 book ai didi

matplotlib - Pandas 条形图-按列指定条形颜色

转载 作者:行者123 更新时间:2023-12-04 13:38:58 28 4
gpt4 key购买 nike

有没有一种简单的方法可以使用Pandas DataFrame.plot(kind='bar')方法按列名指定条形颜色?

我有一个脚本,可以从目录中的几个不同数据文件生成多个DataFrame。例如,它执行以下操作:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pds

data_files = ['a', 'b', 'c', 'd']

df1 = pds.DataFrame(np.random.rand(4,3), columns=data_files[:-1])
df2 = pds.DataFrame(np.random.rand(4,3), columns=data_files[1:])

df1.plot(kind='bar', ax=plt.subplot(121))
df2.plot(kind='bar', ax=plt.subplot(122))

plt.show()

具有以下输出:

不幸的是,不同图中每个标签的列颜色不一致。是否可以传入(filenames:colors)的字典,以便任何特定的列始终具有相同的颜色。例如,我可以想象通过使用Matplotlib color_cycle压缩文件名来创建此文件:
data_files = ['a', 'b', 'c', 'd']
colors = plt.rcParams['axes.color_cycle']
print zip(data_files, colors)

[('a', u'b'), ('b', u'g'), ('c', u'r'), ('d', u'c')]

我可以弄清楚如何使用Matplotlib直接执行此操作:我只是认为可能会有一个更简单的内置解决方案。

编辑:

下面是在纯Matplotlib中工作的部分解决方案。但是,我在IPython笔记本中使用了该笔记本,该笔记本将分发给非程序员同事,并且我想尽量减少过多的绘图代码。
import numpy as np
import matplotlib.pyplot as plt
import pandas as pds

data_files = ['a', 'b', 'c', 'd']
mpl_colors = plt.rcParams['axes.color_cycle']
colors = dict(zip(data_files, mpl_colors))

def bar_plotter(df, colors, sub):
ncols = df.shape[1]
width = 1./(ncols+2.)
starts = df.index.values - width*ncols/2.
plt.subplot(120+sub)
for n, col in enumerate(df):
plt.bar(starts + width*n, df[col].values, color=colors[col],
width=width, label=col)
plt.xticks(df.index.values)
plt.grid()
plt.legend()

df1 = pds.DataFrame(np.random.rand(4,3), columns=data_files[:-1])
df2 = pds.DataFrame(np.random.rand(4,3), columns=data_files[1:])

bar_plotter(df1, colors, 1)
bar_plotter(df2, colors, 2)

plt.show()

最佳答案

您可以传递一个列表作为颜色。与您可以通过字典不同,这需要一点点手工工作才能使它排成一行,但这可能是达成目标的一种较为简洁的方法。

import numpy as np
import matplotlib.pyplot as plt
import pandas as pds

data_files = ['a', 'b', 'c', 'd']

df1 = pds.DataFrame(np.random.rand(4,3), columns=data_files[:-1])
df2 = pds.DataFrame(np.random.rand(4,3), columns=data_files[1:])

color_list = ['b', 'g', 'r', 'c']


df1.plot(kind='bar', ax=plt.subplot(121), color=color_list)
df2.plot(kind='bar', ax=plt.subplot(122), color=color_list[1:])

plt.show()

编辑
Ajean提出了一种简单的方法来从字典中返回正确颜色的列表:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pds

data_files = ['a', 'b', 'c', 'd']
color_list = ['b', 'g', 'r', 'c']
d2c = dict(zip(data_files, color_list))

df1 = pds.DataFrame(np.random.rand(4,3), columns=data_files[:-1])
df2 = pds.DataFrame(np.random.rand(4,3), columns=data_files[1:])

df1.plot(kind='bar', ax=plt.subplot(121), color=map(d2c.get,df1.columns))
df2.plot(kind='bar', ax=plt.subplot(122), color=map(d2c.get,df2.columns))

plt.show()

关于matplotlib - Pandas 条形图-按列指定条形颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25689558/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com