如何使用色图为Pandas数据框绘制彩色图表

18

我有一个像这样的pd.DataFrame

ColumnName
1
1
2
3
1
2
3
1
2
2

我可以使用 df['ColumnName'].plot(style='o') 绘制它。

如何为列中的不同值定义不同的颜色(例如,值1为红色,2为绿色,3为橙色)?我知道这与colormap有关,但我该如何使用它?

一种解决方案是使用每个值的列构建新的DataFrame。但这些值已经排序,我想要确切的顺序只是用不同的颜色着色。

1个回答

35

要绘制数据框的第一列,请尝试像这样:

from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(20, size=20))
cmap = cm.get_cmap('Spectral') # Colour map (there are many others)

fig, ax = plt.subplots(1)
# Now here's the plot. range(len(df)) just makes the x values 1, 2, 3...
# df[0] is then the y values. c sets the colours (same as y values in this
# case). s is the marker size.
ax.scatter(range(len(df)), df[0], c=df[0], s=120, cmap=cmap, edgecolor='None')
plt.show()

导致的结果是:绘图输出


我该如何指定自定义颜色作为色彩映射?例如,如果我想使用只有两种自定义颜色作为色彩映射。 - Nermin
现在在新版本的matplolib中,命令是cmap = cm.Spectral。 - undefined
更多的颜色地图可以在这里找到: https://matplotlib.org/stable/users/explain/colors/colormaps.html - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接