【问题标题】:Creating barplot with dual y-axis [duplicate]使用双 y 轴创建条形图 [重复]
【发布时间】:2021-01-25 15:31:56
【问题描述】:

我正在努力在 R 中制作带有双 y 轴的条形图。我找到了许多相关的帖子,但找不到解决方案。例如,我的数据是这样的:

abc 862054 111552197
xyz 760369 163135388
def 488089 130846735

我关注了这个帖子:Bar Plot with 2 y axes and same x axis in R language 并使用了 highcharter 包来获得这个: 带有 highcharter 的双 y 轴条形图:

但是,我需要一个在两个不同侧面(一个在左侧,一个在右侧)有两个 y 轴的条形图。

有人可以帮我解决这个问题吗?从这篇文章的另一个答案Bar Plot with 2 y axes and same x axis in R language 中,我找到了当 x 是数字列表但在我的情况下 x 是字符串列表而不是数字时的解决方案。

【问题讨论】:

    标签: r bar-chart


    【解决方案1】:

    ggplot2 试试这个tidyverse 方法。双轴图的关键是在要显示在图中的变量之间有一个比例因子。代码如下:

    library(tidyverse)
    #Scaling factor
    sf <- max(df$V2)/max(df$V3)
    #Transform
    DF_long <- df %>%
      mutate(V3 = V3*sf) %>%
      pivot_longer(names_to = "y_new", values_to = "val", V2:V3)
    #Plot
    ggplot(DF_long, aes(x=V1)) +
      geom_bar( aes(y = val, fill = y_new, group = y_new),
                stat="identity", position=position_dodge(),
                color="black", alpha=.6)  +
      scale_fill_manual(values = c("blue", "red")) +
      scale_y_continuous(name = "V2",labels = scales::comma,sec.axis = sec_axis(~./sf, name="V3",
                                                         labels = scales::comma))+
      labs(fill='variable')+
      theme_bw()+
      theme(legend.position = 'top',
            plot.title = element_text(color='black',face='bold',hjust=0.5),
            axis.text = element_text(color='black',face='bold'),
            axis.title = element_text(color='black',face='bold'),
            legend.text = element_text(color='black',face='bold'),
            legend.title = element_text(color='black',face='bold'))+
      ggtitle('My barplot')
    

    输出:

    使用的一些数据:

    #Data
    df <- structure(list(V1 = c("abc", "xyz", "def"), V2 = c(862054L, 760369L, 
    488089L), V3 = c(111552197L, 163135388L, 130846735L)), class = "data.frame", row.names = c(NA, 
    -3L))
    

    【讨论】:

    • 该代码默认生成带有 x 轴标签按字母顺序排列的图形。有没有办法按照我们在 V1 中提到的顺序修改代码以获取 x 轴标签?
    • pivot_longer() 之后添加一个新管道%&gt;% 然后mutate(V1=factor(V1,levels=unique(V1),ordered=T)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    相关资源
    最近更新 更多