【问题标题】:barplot with lineplot - secondary axis带线图的条形图 - 次轴
【发布时间】:2019-10-27 15:50:30
【问题描述】:

在参考了多个链接之后,我得到了下面的代码,但是我仍然没有成功获得带有标签的行。我怀疑sec.axis 转换中的一些错误,但我无法弄清楚。

# dummy data
df_dummy = data.frame('Plan_code'=c('A','B','C','D','E','F','G'),
'Total'=c(191432,180241,99164,58443,56616,29579,19510),'STP'=c(41,40,44,37,37,37,45))

# creation of plot 
[![g <- ggplot(data = df_dummy, aes(x = Plan_code, y = Total)) +
  geom_col(aes(fill = 'Total')) +
  geom_line(data = df_dummy, aes(x = Plan_code, y = STP,group=1)) +
  geom_point(data = df_dummy, aes(x = Plan_code,y=STP)) +
  geom_label(data = df_dummy, aes(x = Plan_code, y = STP, fill = Plan_code, label = paste0('%', STP)), color = 'white', vjust = 1.6, size = 3) +
  scale_y_continuous(sec.axis = sec_axis(~. / 2000, name = 'PERCENT')) +
labs(fill = NULL, color = NULL) +
  theme_minimal()
print(g)][1]][1]

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    喜欢吗?

    g <- ggplot(data = df_dummy, aes(x = Plan_code, y = Total)) +
         geom_col(aes(fill = 'Total'))  +
         geom_point(data = df_dummy, aes(x = Plan_code,y=STP * 2000)) +
         geom_label(data = df_dummy, aes(x = Plan_code, y = STP *2000, fill = Plan_code, label = paste0('%', STP)), color = 'white', vjust = 1.6, size = 3) +
         scale_y_continuous(sec.axis = sec_axis(~. / 2000, name = 'PERCENT'))+
         geom_line(data = df_dummy, aes(x = Plan_code, y = STP * 2000,group=1), col = 'blue') +
         theme(axis.text.y.right = element_text(color =  'blue'),axis.title.y.right = element_text(color =  'blue'))
         labs(fill = NULL, color = NULL) +
         theme_minimal()
    

    我只是将您的数据乘以 2000,因此绝对 y 坐标是正确的。 我改变了颜色。

    【讨论】:

    • 看起来和我想要的很接近~你能解释一下乘以 2000 的原因吗?我也可以在点附近找到标签吗?我尝试调整 vjust 并把它弄起来,但它对我不起作用。我从另一个堆栈中获取了这个代码 sn-p,因此我不需要 A、B、C 等的颜色编码
    • 乘法背后的原因与您在创建第二个轴时所做的相反。您将 Axis-Labels 划分为 2000 年,以便它们显示百分比值。您并没有真正引入第二个比例,“绝对”y 值保持不变。因此,要以正确的相对距离显示您的百分比值,您必须将它们转换为您的“绝对”y 轴,即您的总轴。
    • 我以同样的方式改变了标签 y,遵循同样的推理。起初,我以为你是故意把你的标签放在那里的。 (让人想起this Question)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 2016-04-24
    • 2016-11-03
    相关资源
    最近更新 更多