【问题标题】:How to use colormaps to color plots of Pandas DataFrames如何使用颜色图为 Pandas DataFrames 的图着色
【发布时间】:2014-09-09 09:33:15
【问题描述】:
我有一个像这样的pd.DataFrame:
ColumnName
1
1
2
3
1
2
3
1
2
2
我可以用df['ColumnName'].plot(style='o')绘制它
如何为列中的不同值定义不同的颜色(例如,红色代表值 1,绿色代表 2,橙色代表 3)。我知道它与colormap 有关,但我该如何使用它呢?
一种解决方案是使用每个值的列构造一个新的DataFrame。但是这些值是排序的,我希望这个序列只是用不同的颜色着色。
【问题讨论】:
标签:
python
colors
plot
pandas
dataframe
【解决方案1】:
要绘制数据框中的第一列,请尝试以下操作:
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()
结果为: