Python 如何使用颜色图为 Pandas DataFrame 的绘图着色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25741214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:34:44  来源:igfitidea点击:

How to use colormaps to color plots of Pandas DataFrames

pythoncolorsplotpandasdataframe

提问by Guforu

I have a pd.DataFramelike this one:

我有一个pd.DataFrame这样的:

ColumnName
1
1
2
3
1
2
3
1
2
2

I can plot it with df['ColumnName'].plot(style='o')

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

How I can define different colors for the different values in the column (for example red for value 1, green for 2, orange for 3). I know it has to do with colormap, but how I can use it?

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

An solution is to construct a new DataFramewith the columns of every value. But these values are sorted and I want have exactly this sequence just colored in the different colors.

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

采纳答案by LondonRob

To plot the first column from your dataframe, try something like this:

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

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()

Which results in:Plot output

结果是:绘图输出