python - 如何使用颜色图为 Pandas DataFrames 的绘图着色

标签 python colors plot pandas dataframe

我有一个像这样的 pd.DataFrame:

ColumnName
1
1
2
3
1
2
3
1
2
2

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

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

一个解决方案是用每个值的列构造一个新的DataFrame。但是这些值是经过排序的,我希望这个序列只是用不同的颜色着色。

最佳答案

要绘制数据框中的第一列,请尝试如下操作:

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

关于python - 如何使用颜色图为 Pandas DataFrames 的绘图着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25741214/

相关文章:

python - 使用python获取密码

python - 在 PyCharm 中运行 Django 应用测试

swift - 表格 View 单元格在滚动 Swift 时改变颜色

java - 为什么 JFrame 中的绘图颜色没有更新?

python - matplotlib 显示具有自定义日期格式和间隔的 x 轴

python - python中列表概念的列表

python - 解包嵌套元组如何在 Python 中工作?

javascript - 通过饱和度计算新的 RGB

python - 用于从 Matplotlib 绘图的标准 ASCII 文件格式

python - Matplotlib:使用 twinx() 和 cla() 清除第二个轴后无法重新绘制第一个轴