Change colour of colorbar in Python Matplotlib

pau*_*a.n 6 python matplotlib scatter-plot colorbar

I have a code that gives me a scatter plot of predicted vs actual values as a function of concentration. The data is pulled from an excel csv spreadsheet.

This is the code:

import matplotlib.pyplot as plt
from numpy import loadtxt


dataset = loadtxt("ColorPlot.csv", delimiter=',')
x = dataset[:,0]
y = dataset[:,1]
z = dataset[:,2]

scaled_z = (z - z.min()) / z.ptp()

colors = plt.cm.viridis(scaled_z)
sc=plt.scatter(x, y, c=colors)
plt.clim(0, 100)
plt.colorbar()
plt.xlabel("Actual")
plt.ylabel("Predicted")

plt.show()
Run Code Online (Sandbox Code Playgroud)

And with this I get a nice graph: 在此输入图像描述

However if I change the color to something like

colors = plt.cm.plasma(scaled_z)
Run Code Online (Sandbox Code Playgroud)

I get the graph below but the colorbar remains unchanged.

在此输入图像描述

I've tried lots of different things like cmap or edgecolors but I don't know how to change it. And I want to keep the code as simple as it currently is because I want to readily change the third variable of z based on my excel spreadsheet data.

Is there also a way for the scale of the colorbar to pick up what the scale is from the excel spreadsheet without me manually specifying 0-100?

Val*_*_Bo 8

要获得正确的颜色条,请使用以下代码:

colormap = plt.cm.get_cmap('plasma') # 'plasma' or 'viridis'
colors = colormap(scaled_z)
sc = plt.scatter(x, y, c=colors)
sm = plt.cm.ScalarMappable(cmap=colormap)
sm.set_clim(vmin=0, vmax=100)
plt.colorbar(sm)
plt.xlabel("Actual")
plt.ylabel("Predicted")
plt.show()
Run Code Online (Sandbox Code Playgroud)

对于我随机生成的数据,我得到了以下图:

在此输入图像描述

现在替换'plasma''viridis'检查其他变体。