0

I am trying to understand how this works

Dataframe is "result"

Column in "result" is Time, Column1, Column2

I am able to plot only a single line from the Column1 from the code below:

(p9.ggplot(data=result,
           mapping=p9.aes(x='Time', y='Column1'))
+ p9.geom_point(alpha=0.5)
+ p9.scale_x_datetime(breaks=date_breaks('12 hour'))
)

How to write the code if I wanted it to include Column2? Means plot 2 lines in the chart?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
sam
  • 115
  • 2
  • 10
  • As an R and ggplot2 user I'm not familiar with `plotnine`. But in ggplot2 something like `+ p9.geom_point(mapping=p9.aes(x='Time', y='Column2'), alpha=0.5)` would add a second geom_point layer with the y values given by Column2. – stefan Apr 08 '21 at 08:44
  • Yes, it seems to be working! But the thing is, both will be sharing the same y axis. It will be problematic in the vase where column 1 and 2 is not using the same units or having large difference range. Thanks anyway for the answer. – sam Apr 08 '21 at 09:17
  • I see. Secondary axes are a bit tricky in ggplot2. In ggplot2 you could add a secondary y axis via the `sec.axis` argument of `scale_y_continuous`. However, I just had a look at the plotnine documentation and it looks like this feature has not been implemented in plotnine. ): – stefan Apr 08 '21 at 09:35
  • In that case, is there anything else that I could use to achieve it? Seaborn? – sam Apr 08 '21 at 13:50

2 Answers2

1

Plotnine's current API (as of 2022-08-09) doesn't include a secondary axis, so this is not possible to do. It is a feature that has been requested several times though, and looks like it is in the roadmap for the next major release.

In any case, if you want to keep with the ggplot2 style you will have to move to R and use the sec.axis of scale_y_continous (you can see several examples here.

If you want to stay in Python, you can just go directly to matplotlib, as secondary axes are supported using the .twinx() method. The working example for your case would be:


import matplotlib.pyplot as plt

ax = result.plot(x='Date', y='Column1', color='blue', legend=False)
sec_axis = ax.twinx()
result.plot(x='Date', y='Column2', ax=sec_axis, color='red', legend=False)
ax.figure.legend()
plt.show()

0

Why not:


(p9.ggplot(data=result.melt(id_vars = 'Time'),
           mapping=p9.aes(x='Time', y='value', color='variable', group = 'variable'))
+ p9.geom_point(alpha=0.5)
+ p9.scale_x_datetime(breaks=date_breaks('12 hour'))
)
Timi Bennatan
  • 71
  • 1
  • 10