在基于 pandas 列数值的情况下填充绘图间隔

huangapple go评论68阅读模式
英文:

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_valuesample的关系,并用阴影填充图形的背景,以不同颜色表示每个段的区域。例如,从图形底部到顶部,用蓝色表示"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()

绘图

在基于 pandas 列数值的情况下填充绘图间隔

英文:

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

在基于 pandas 列数值的情况下填充绘图间隔

huangapple
  • 本文由 发表于 2023年4月4日 10:47:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75925148.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定