如何使用颜色映射为Pandas DataFrame绘图上色

18 投票
1 回答
58457 浏览
提问于 2025-04-20 15:02

我有一个 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()

这样做会得到一个图像,像这样:Plot output

撰写回答