Plotnine : 如何在一行上创建两个图例

问题描述

我正在使用 plotnine 创建双条形 + 折线图(见下文)。我希望这两个图例像下面的 R 示例一样出现在一行中。这可以用 plotnine 来完成吗?下面的示例代码

plotnine 代码(我拥有的):

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.5,0.4,0.2,0.6,-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','tty': (2.7,2.7,3.2,2.3,2.1,3.0,2.5,3.1,3.3,2.4,1.9,1.7,2.2,1.4,-6.3,-3.7,-1.1)
})
tty = pd.melt(tty,value_vars=['tty'])

p = (ggplot()
  + theme_light()
  + geom_bar(qrtly,aes(x='date',y='value',fill='variable'),stat='identity',position='dodge')
  + geom_line(tty,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

结果:

enter image description here

R 代码(我想要的):

library(ggplot2)


df = data.frame(
        date = seq(as.Date('2015-12-1'),as.Date('2020-12-1'),by='quarter'),qrtly = c(0.6,3.1),tty = c(2.7,-1.1)
)

ggplot(df) +
    theme_light() +
    geom_bar(aes(x=date,y=qrtly,fill='quarterly'),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(),)

结果:

enter image description here

解决方法

我刚刚通过查阅文档发现了这一点,但您想要的设置是

2

您可以在此处找到更多信息: https://plotnine.readthedocs.io/en/stable/generated/plotnine.themes.theme.html