英文:
Matplotlib's stackplot change colors for overlapping regions
问题
使用Matplotlib的stackplot
绘制堆叠面积图时,如果一组y
值中有负数,那么该区域会与下面的区域重叠。例如:
import matplotlib.pyplot as plt
plt.stackplot([1,2,3], [1,2,3], [1,0,-1])
plt.show()
您可以看到顶部的y
值为橙色。由于最右边的y
值为-1
,它与蓝色区域重叠。对于我的需求来说这是可以的。但是,我需要使这种重叠明显,以便区分它与蓝色区域仅仅保持在x=2.0
到x=3.0
之间的y=2.0
不同,而橙色区域为正数。是否可以将这种重叠设置为不同的颜色?
英文:
When I draw a stacked area plot using Matplotlib's stackplot
, if a set of y
values has a negative number in it, then that area will overlap with the area underneath. For example:
import matplotlib.pyplot as plt
plt.stackplot([1,2,3], [1,2,3], [1,0,-1])
plt.show()
You can see the top set of y
values are in orange. Since the right most y
value is -1
, it overlaps with the blue region. This is fine for my purposes. Except, I need that to be clear it's an overlap as opposed to the blue region just stayed at y=2.0
from x=2.0
to x=3.0
and the orange area is positive. Can overlaps like this be set to a different color?
答案1
得分: 0
可以将重叠的部分设置成不同的颜色吗?
是的,您可以将第二个 y 数据分成两次绘制:
import matplotlib.pyplot as plt
import numpy as np
y1 = [1,2,3]
y2 = [1,0,-1]
polys = plt.stackplot([1,2,3], y1, np.maximum(y2, 0), np.minimum(y2, 0))
我认为更好的解决方案是将颜色设置为半透明,也可以添加阴影效果:
polys = plt.stackplot([1,2,3], [1,2,3], [1,0,-1], alpha=0.3)
for poly, hatch in zip(polys, ['|', '-']):
poly.set_hatch(hatch)
poly.set_edgecolor(poly.get_facecolor())
英文:
> Can overlaps like this be set to a different color?
Yes, you could draw the second y data in two runs:
import matplotlib.pyplot as plt
import numpy as np
y1 = [1,2,3]
y2 = [1,0,-1]
polys = plt.stackplot([1,2,3], y1, np.maximum(y2, 0), np.minimum(y2, 0))
I think, however, a better solution would be to make the colors semi-transpartent, maybe with additional hatching:
polys = plt.stackplot([1,2,3], [1,2,3], [1,0,-1], alpha=0.3)
for poly, hatch in zip(polys, ['|', '-']):
poly.set_hatch(hatch)
poly.set_edgecolor(poly.get_facecolor())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论