brb
brb

Reputation: 1179

Plotnine : How to create two legends on a single line

I am using plotnine to create a dual bar + line chart (see below). I would like the two legends to appear in a single line like the R example below. Can this be done with plotnine? Sample code below:

plotnine code (what I have):

import numpy as np
import pandas as pd
from plotnine import *
from mizani.formatters import date_format

qrtly = pd.DataFrame({
        'date':pd.date_range(start='1/1/2015', periods=21, freq='Q'),
        'qrtly': (0.6,0.9,0.7,0.1,1.0,0.3,0.7,1.0,0.5,0.9,0.9,0.4,0.2,0.5,0.7,0.6,0.4,-0.3,-7.0,3.4,3.1)
})
qrtly = pd.melt(qrtly, id_vars=['date'], value_vars=['qrtly'])

tty = pd.DataFrame({
        'date':pd.date_range(start='1/1/2015', periods=21, freq='Q'),
        'tty': (2.7,2.7,3.2,2.3,2.7,2.1,2.1,3.0,2.5,3.1,3.3,2.7,2.4,1.9,1.7,1.9,2.2,1.4,-6.3,-3.7,-1.1)
})
tty = pd.melt(tty, id_vars=['date'], value_vars=['tty'])

p = (ggplot()
  + theme_light()
  + geom_bar(qrtly, aes(x='date',y='value', fill='variable'), stat='identity', position='dodge')
  + geom_line(tty, aes(x='date',y='value',color='variable'))
  + labs(x=None,y=None)
  + scale_x_datetime(breaks='1 year', labels=date_format('%Y'), expand=(0,0))
  + scale_fill_manual('#002147')
  + scale_color_manual('#800000')
  + guides(color = guide_legend(nrow = 1))
  + guides(fill = guide_legend(nrow = 1))
  + theme(
        legend_direction = 'horizontal',
        legend_position = 'bottom',
        legend_title = element_blank(),
    )

)
p

result: enter image description here

R code (what I want):

library(ggplot2)


df = data.frame(
        date = seq(as.Date('2015-12-1'), as.Date('2020-12-1'), by='quarter'),
        qrtly = c(0.6,0.9,0.7,0.1,1.0,0.3,0.7,1.0,0.5,0.9,0.9,0.4,0.2,0.5,0.7,0.6,0.4,-0.3,-7.0,3.4,3.1),
        tty = c(2.7,2.7,3.2,2.3,2.7,2.1,2.1,3.0,2.5,3.1,3.3,2.7,2.4,1.9,1.7,1.9,2.2,1.4,-6.3,-3.7,-1.1)
)

ggplot(df) +
    theme_light() +
    geom_bar(aes(x=date, y=qrtly, fill='quarterly'), stat='identity', position='dodge') +
    geom_line(aes(x=date, y=tty, group=1, color='tty'), size=1) +
    labs(x=NULL, y=NULL) +
    scale_fill_manual(values=c('#002147')) +
    scale_color_manual(values=c('#800000')) +
    guides(color = guide_legend(nrow = 1)) +
    guides(fill = guide_legend(nrow = 1)) +
    theme(
        legend.direction = 'horizontal',
        legend.position = 'bottom',
        legend.title = element_blank(),
    )

result:

enter image description here

Upvotes: 1

Views: 786

Answers (1)

Mufan Bill Li
Mufan Bill Li

Reputation: 36

I just figured out this out by going into the documentation, but the setting you want is

+ theme(legend_box = 'horizontal')

You can find more information here: https://plotnine.readthedocs.io/en/stable/generated/plotnine.themes.theme.html

Upvotes: 2

Related Questions