1

I have started using plotnine and would like to create a chart with a red area above 40 and a blue area below -40.

chart with red and blue rectangles

I was able to approximate it with the following code, but it seems hacky. What is the "correct" way to do this?

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) 

1 Answers1

0

You can add a rectangular area with plotnine using the geom geom_rect().

+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

(Or just transform thegeom_hlines to be above 40 and below -40)

Zero Pancakes
  • 276
  • 2
  • 12