Matplotlib 更改图形颜色

问题描述

我想在下一个图表中更改颜色。我需要黄色为绿色,绿色为红色,紫色为蓝色。

enter image description here

我有一个代码

fig = plt.figure()
ax = fig.add_subplot(111)

scatter = ax.scatter( kmeans['Revenue'],kmeans['Frequency'],c=kmeans['Cluster'],s=15)
                
ax.set_xlabel('Recency')
ax.set_ylabel('Frequency')
plt.colorbar(scatter)

如何更改颜色?

解决方法

如果您要阅读 scatter 的文档,那么您会看到 cmap 的选项 colormap

如果您使用 Google matplotlib scatter colormap 那么您会发现 Choosing Colormaps in Matplotlib

它显示了预定义的颜色图,看来您需要 brg


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

random = np.random.sample((100,3))
kmeans = pd.DataFrame(random,columns=['Revenue','Frequency','Cluster'])

fig = plt.figure()
ax = fig.add_subplot(111)

scatter = ax.scatter( kmeans['Revenue'],kmeans['Frequency'],c=kmeans['Cluster'],s=15,cmap='brg')
                
ax.set_xlabel('Recency')
ax.set_ylabel('Frequency')
plt.colorbar(scatter)

plt.show()

enter image description here