【问题标题】:Python plotnine - adding a rectangular areaPython plotnine - 添加一个矩形区域
【发布时间】:2021-02-04 10:22:03
【问题描述】:

我已经开始使用 plotnine 并想创建一个红色区域高于 40 和蓝色区域低于 -40 的图表。

chart with red and blue rectangles

我可以用下面的代码来近似它,但它看起来很老套。这样做的“正确”方法是什么?

import pandas as pd
from plotnine import *

vals = np.random.randint(-50, 50, size=20)
df = pd.DataFrame({"val":vals})
ggplot(df, aes(x=df.index, y = 'val')) \
   + geom_line() \
   + geom_hline(yintercept=40, size=20, colour='red', alpha=0.5) \
   + geom_hline(yintercept=-40, size=20, colour='blue', alpha=0.5) 

【问题讨论】:

  • 也许是 geom_rect()?
  • 非常感谢,成功了。我不知道为什么它以前不起作用。
  • 我将在下面输入它作为完成这篇文章的答案

标签: python plotnine


【解决方案1】:

您可以使用 geom geom_rect() 添加一个带有 plotnine 的矩形区域。

+geom_rect(data = dfwithnumbersyoulike, aes(xmin = yourxmin, xmax = yourxmax, ymin = yourymin, ymax = yourymax, fill = #ff0000, alpha = 0.7)) #red
+geom_rect(data = dfwithnumbersyoulike2, aes(xmin = yourxmin2, xmax = yourxmax2, ymin = yourymin2, ymax = yourymax2, fill = #0000ff, alpha = 0.7)) #blue

(或者只是将geom_hlines 转换为高于40 并低于-40

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 2017-03-18
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多