【问题标题】:R Overlay Line Plot on BarPlot with 2 axes带有 2 个轴的 BarPlot 上的 R 叠加线图
【发布时间】:2019-03-08 06:02:20
【问题描述】:

我有以下代码,它只产生一个没有线条的条形图。如何调整此代码以获取辅助线?

library(ggplot2)
p1 <- ggplot()
p1 <- p1 + geom_bar(data=subset(df, Year==2006), aes(x=factor(State),y=Rate), stat = "identity")
p1 <- p1 + xlab("State") + ylab("Rate") + theme(axis.text.x = element_text(angle = 60, hjust = 1)) 
p1 <- p1 +  geom_line(data = subset(df, Year==2006),  aes(x=factor(State),y=Total.Poverty/1000),colour = "blue") 
p1 <- p1 + scale_y_continuous(sec.axis = sec_axis(~.*1000, name = "Total Poverty"))
print(p1)

我查看了ggplot2 overlay of barplot and line plot,但我仍然无法弄清楚为什么情节没有显示这条线。

【问题讨论】:

    标签: r


    【解决方案1】:

    你应该提供一个最小的数据集来重现你的问题,所以我无法测试我的解决方案,但我认为这是因为因子尺度上的线不起作用,所以你应该使用:

    p1 <- p1 +  geom_line(data = subset(df, Year == 2006),  
                          aes(x = State, y = Total.Poverty / 1000), colour = "blue")
    

    改为。

    【讨论】:

    • 我试过了,没有成功。让我告诉你我有什么。在原始线程中重新附加文件。 df
    【解决方案2】:

    必须在代码中添加 group = 1

    library(ggplot2)
    p1 <- ggplot()
    p1 <- p1 + geom_bar(data=subset(df, Year==2006), aes(x=factor(State),y=Rate), stat = "identity")
    p1 <- p1 + xlab("State") + ylab("Rate") + theme(axis.text.x = element_text(angle = 60, hjust = 1)) 
    p1 <- p1 +  geom_line(data = subset(df, Year==2006),  aes(x=factor(State),y=Total.Poverty/1000),colour = "blue", group = 1) 
    p1 <- p1 + scale_y_continuous(sec.axis = sec_axis(~.*1000, name = "Total Poverty"))
    print(p1)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      相关资源
      最近更新 更多