![](/img/trans.png)
[英]How to set different colors for specific columns in matplotlib bar chart?
[英]Bar Chart with Different Widths and Colors in matplotlib (Bar Mekko chart)
我正在嘗試在matplotlib中創建所謂的條形圖 。
我發現matplotlib中的條形圖可以解決這個問題,但是我錯過了如何顯示以0為中心的顏色條。
這是我的嘗試,評論了我仍然缺少的片段:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.cm as cm
%matplotlib inline
x = np.array([0. , 0.4512135, 0.760715 , 0.775948 , 0.977063 , 1.170482 ,
1.229812 , 1.3009845, 1.347207 , 1.4155705, 1.928897 ])
bin_width = np.diff(x)
y = np.array([ 0.40048296, 1.11131896, 0.30525134, 3.86793415, 21.80974083,
11.88354534, 13.84599687, 9.7484865 , 9.5418679 , 22.39983675])
z = np.array([0. , 0.4512135, -0.760715 , 0.775948 , 0.977063 , 1.170482 ,
1.229812 , 1.3009845, 1.347207 , -1.4155705])
fig, ax1 = plt.subplots(1)
#?# offset = mcolors.DivergingNorm(vcenter=0.)
# Colorbar needs to be centered (0 should be yellow always)
colors = plt.cm.RdYlBu(z) # offset???
bar_plot = ax1.bar(x[:-1],y,
color=colors,
width=bin_width,
align='edge')
#?# sm = cm.ScalarMappable(cmap=my_cmap, norm=plt.Normalize(0,max(data_color)))
#?# sm.set_array([])
#?# cbar = plt.colorbar(sm)
plt.ylabel("y")
plt.show()
# plt.colorbar(mappable=bar_plot, ax=ax1) ??
似乎您已經找到了所有必要的點點滴滴,並以錯誤的方式將它們修補在一起。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.cm as cm
x = np.array([0. , 0.4512135, 0.760715 , 0.775948 , 0.977063 , 1.170482 ,
1.229812 , 1.3009845, 1.347207 , 1.4155705, 1.928897 ])
bin_width = np.diff(x)
y = np.array([ 0.40048296, 1.11131896, 0.30525134, 3.86793415, 21.80974083,
11.88354534, 13.84599687, 9.7484865 , 9.5418679 , 22.39983675])
z = np.array([0. , 0.4512135, -0.760715 , 0.775948 , 0.977063 , 1.170482 ,
1.229812 , 1.3009845, 1.347207 , -1.4155705])
fig, ax = plt.subplots()
cmap = plt.cm.RdYlBu
norm = mcolors.DivergingNorm(vmin=z.min(), vcenter=0., vmax=z.max())
sm = cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
bar_plot = ax.bar(x[:-1], y, color=cmap(norm(z)), width=bin_width, align='edge')
cbar = fig.colorbar(sm)
ax.set_ylabel("y")
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.