带有自定义渐变颜色的单堆积条形图

2024-05-15 00:12:27 发布

您现在位置:Python中文网/ 问答频道 /正文

Here's what I came up with by plotting thick line segments.

下面是我通过绘制粗线段得出的结果。 颜色为蓝色,alpha变化为0<;alpha<;1。你知道吗

我的解决方法没有像我所希望的那样工作,因为我没有图例(我想要一个图例,它在不同的alpha处显示蓝色的渐变)。你知道吗

另外,我发现matplotlib的尺度很有趣。应该没有重叠的栏,但如果我调整窗口大小,线段之间的间隙将发生变化。This is the same figure as the earlier one, just after I've resized the figure window with my mouse.这是同一个数字,刚才我用鼠标调整了图形窗口的大小。你知道吗

我不确定是否有更好的方法来实现这一点,或者是否有一个不同的包,我可以使用。 下面是我正在使用的代码片段。你知道吗

import matplotlib.pyplot as plt
x1  =[0, 19, 39, 46, 60, 79]
x2 = [19, 39, 46, 60, 79, 90]
alpha_list = [-0.8402, -0.6652, 0.0, -0.5106, -0.8074, 0.0]
plt.figure()
for idx,x in enumerate(x1):
    plt.plot([x1[idx],x2[idx]],[0,0],color = 'blue',alpha=alpha_list[idx],linewidth =20)
plt.show()

Tags: 方法ltalphamatplotlib颜色绘制pltlist
2条回答

我认为解决方法是使用plt.barh。下面是一个使用标准化颜色贴图的示例。每种颜色在传递到plt.barh之前都会转换为RGBA。你知道吗

import matplotlib.pyplot as plt
from matplotlib import colors
import matplotlib.cm as cmx

x1  =[0, 19, 39, 46, 60, 79]
x2 = [19, 39, 46, 60, 79, 90]

values = range(len(x1))
jet = cm = plt.get_cmap('jet') 
cNorm  = colors.Normalize(vmin=0, vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)

fig, ax = plt.subplots()

for idx, x, y in zip(values,x1, x2):          
    colorVal = scalarMap.to_rgba(values[idx])  
    start = x
    end = y
    width=end-start
    ax.barh(y = 0, width = width, left=start, height = 0.1, label = str(idx), color=colorVal)         
ax.set_ylim(-.5,0.5)
ax.legend()

返回: enter image description here

如果你真的想改变一种颜色的alpha透明度,你只需要把最后一个元素的alpha_list[idx]输入到RGBA元组colorVal。由于某些原因,RGBA不喜欢负的alpha值,所以请注意,我将它们全部改为正

fig, ax = plt.subplots()
alpha_list = [0.8402, 0.6652, 0.01, 0.5106, 0.8074, 0.0]
for idx, x, y in zip(values,x1, x2):          
    colorVal = (0.0, 0.3, 1.0, alpha_list[idx])
    start = x
    end = y
    width=end-start
    ax.barh(y = 0, width = width, left=start, height = 0.1, label = str(idx), color=colorVal)         


ax.set_ylim(-.5,0.5)
ax.legend()

enter image description here

我想alpha只是一个使用不同深浅蓝色的变通方法?在这种情况下,可以使用Blues颜色映射。
可以使用LineCollection绘制几条线。你知道吗

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

x1  =[0, 19, 39, 46, 60, 79]
x2 = [19, 39, 46, 60, 79, 90]
alpha_list = [-0.8402, -0.6652, 0.0, -0.5106, -0.8074, 0.0]

verts = np.dstack((np.c_[x1, x2], np.zeros((len(x1), 2))))

fig, ax = plt.subplots()
lc = LineCollection(verts, linewidth=40, cmap="Blues_r", array=np.array(alpha_list))
ax.add_collection(lc)

ax.autoscale()
ax.set_ylim(-1,1)
fig.colorbar(lc)
plt.show()

enter image description here

相关问题 更多 >

    热门问题