简体   繁体   中英

How to plot a graph from 2 columns in a dataframe using plotnine?

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?

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'))
)

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 exampleshere .

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM