sam
sam

Reputation: 115

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?

Upvotes: 0

Views: 1665

Answers (2)

Alejandro Fontal
Alejandro Fontal

Reputation: 11

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

Upvotes: 1

Timi Bennatan
Timi Bennatan

Reputation: 91

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

Upvotes: 0

Related Questions