简体   繁体   中英

Fill a matplotlib contour plot

With the following code I have obtained the following contour map:

fig, ax = plt.subplots()
x = np.arange(431)
y = np.arange(225)
Y, X = np.meshgrid(y, x)
values = df["Appearance_percentage"].values
values2d = np.reshape(values, (431, 225))
ax.set_ylim(225, 0)

plt.style.use('seaborn-white')
ax.set_title('Mapa contour de probabilitat de trobar núvols')
plt.contour(X, Y, values2d, 30, cmap='RdGy')
plt.colorbar()
plt.savefig("contourmap.png")

等高线图

I would like to know if I could fill the areas between the lines so that there are no white spaces in the color bar and the map is more attractive.

I tried doing df["Appearance_percentage_contourmap"] = round(df["Appearance_percentage"]) and then values = df["Appearance_percentage_contourmap"].values and I'm still obtaining the same map with lots of white areas.

Just replace plt.contour with plt.contourf , where the "f" at the end means "fill".

Here is an example:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(100)
y = np.arange(100)
Y, X = np.meshgrid(y, x)
values = np.outer(x, y)

fig, ax = plt.subplots()
plt.contourf(X, Y, values, 30, cmap='RdGy')
plt.colorbar()

填充等高线图。

You may also want to emphasis the contour lines with:

x = np.arange(100)
y = np.arange(100)
Y, X = np.meshgrid(y, x)
values = np.outer(x, y)

fig, ax = plt.subplots()
c1 = plt.contourf(X, Y, values, 30, cmap='RdGy')
c2 = plt.contour(X, Y, values, 30, cmap='Greys')
plt.colorbar(c1)

用等高线填充等高线图。

plt.contour() creates an isoline connecting all the places with an equal interpolated value. So, it searches places where the appearance is eg 6% and connects these with a line. If you set levels=30 there will be 30 such lines drawn. plt.contour() does a lot of effort to create a colorbar that shows the value for each line. If you don't want such a colorbar, you can create a custom colorbar using the same values.

You can create a custom colorbar as follows:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable

fig, ax = plt.subplots()
x = np.arange(431)
y = np.arange(225)
Y, X = np.meshgrid(y, x)
values = np.random.randn(431, 225).cumsum(axis=0).cumsum(axis=1).ravel()
values -= values.min()
values2d = np.reshape(values, (431, 225))
ax.set_ylim(225, 0)

plt.style.use('seaborn-white')
ax.set_title('Mapa contour de probabilitat de trobar núvols')
plt.contour(X, Y, values2d, 30, cmap='RdGy')
sm = ScalarMappable(norm=plt.Normalize(values.min(), values.max()), cmap='RdGy')
plt.colorbar(sm)
plt.show()

示例图

PS:Please don't round the values (as in df["Appearance_percentage_contourmap"] = round(df["Appearance_percentage"]) ), because that introduces artificial inaccuracies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM