英文:
Filling between intervals on plot based on pandas column value
问题
我有一个示例DataFrame:
df =
segment sample data_value
first 1 28
first 2 53
first 3 19
second 4 50
second 5 39
second 6 61
third 7 22
third 8 49
third 9 34
我想要绘制data_value
与sample
的关系,并用阴影填充图形的背景,以不同颜色表示每个段的区域。例如,从图形底部到顶部,用蓝色表示"first"段,绿色表示"second"段等,还要包括图例。
我可以使用以下代码:
plt.scatter(df['sample'], df['data_value'])
但我不知道如何以编程方式填充图形的背景,以在不同颜色下显示随时间的变化。是否可以使用fill_between()
来实现这一点?
任何帮助都将非常感谢。谢谢!
英文:
I have an example DataFrame:
df =
segment sample data_value
first 1 28
first 2 53
first 3 19
second 4 50
second 5 39
second 6 61
third 7 22
third 8 49
third 9 34
I'd like to plot data_value
vs. sample
with plot shading (with the background of the plot indicating each segment with a different color. For example, from the bottom of the graph to the top, shading the background of the plot for the "first" segment as blue, "second" segment as green, etc. with the legend.
I can do:
plt.scatter(df['sample'], df['data_value'])
but am struggling on how to fill the backgrounds for each segment of the plot in a color-coded way to show the progression over time. Could I use fill_between()
somehow?
Any help would be awesome. Thanks!
答案1
得分: 1
这是您正在寻找的内容吗?如JohanC建议,您可以使用axhspan
创建如下所示的带状区域...
注意:我假设样本的顺序是升序的,因此代码将有效...
plt.scatter(df['data_value'], df['sample'])
colors = ['blue', 'green', 'red']
start = 0
for i, segs in enumerate(df.segment.unique()):
plt.axhspan(start, df[df.segment == segs]['sample'].max(), facecolor=colors[i], alpha=0.2)
start = df[df.segment == segs]['sample'].max()
绘图
英文:
Is this what you are looking for? As suggested by JohanC, you can use axhspan
to create bands as shown below...
Note: I am assuming that the order of sample is ascending, so that the code will work...
plt.scatter(df['data_value'], df['sample'])
colors = ['blue', 'green', 'red']
start = 0
for i, segs in enumerate(df.segment.unique()):
plt.axhspan(start, df[df.segment == segs]['sample'].max(), facecolor=colors[i], alpha=0.2)
start=df[df.segment == segs]['sample'].max()
Plot
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论