ggplot子图,带有R中的分类和数字

时间:2017-10-30 17:32:19

标签: r ggplot2

我有一张下表,我需要将其绘制成图(x轴为一周,y轴为百分比)。我的下面的代码只是给我一个消息。有人可以帮我解决这个问题吗?

感谢任何帮助。

dfx1:

Year  State  Cty        Week   ac_sum    percent
1998  KS     Coffey     10-1   79        6.4
1998  KS     Coffey     10-3   764       62
1998  KS     Coffey     10-4   951       77.2
1998  KS     Coffey     10-5   1015      82.4
1998  KS     Coffey     11-2   1231      100
1998  KS     Crawford   10-3   79        6.1
1998  KS     Crawford   10-4   764       15.8
1998  KS     Crawford   10-5   951       84.1
1998  KS     Crawford   11-2   1015      100
.
.
.
.


gg <- ggplot(dfx1, aes(Week,percent, col=Year))
gg <- gg + geom_line()
gg <- gg + facet_wrap(~Cty, 2, scales = "fixed")
gg <- gg + xlim(c(min(dfx1$Week), max(dfx1$Week)))
plot(gg)

geom_path: Each group consists of only one observation. Do you need to
adjust the group aesthetic?

2 个答案:

答案 0 :(得分:1)

这是你想要的吗?

dfx1 <- read.table(text="Year  State  Cty        Week   ac_sum    percent
1998  KS     Coffey     10-1   79        6.4
1998  KS     Coffey     10-3   764       62
1998  KS     Coffey     10-4   951       77.2
1998  KS     Coffey     10-5   1015      82.4
1998  KS     Coffey     11-2   1231      100
1998  KS     Crawford   10-3   79        6.1
1998  KS     Crawford   10-4   764       15.8
1998  KS     Crawford   10-5   951       84.1
1998  KS     Crawford   11-2   1015      100", header=T)

library(ggplot2)
ggplot(dfx1, aes(Week,percent, col=Year)) + 
    geom_point() +
    facet_wrap(~Cty, 2, scales = "fixed") 

enter image description here

ggplot(dfx1, aes(Week,percent, col=Year, group=1)) + 
    geom_point() + geom_line() +
    facet_wrap(~Cty, 2, scales = "fixed") 

enter image description here

答案 1 :(得分:1)

您可以查看其他答案,例如this one,以确定您的情节中缺少group = Year。添加它将为您提供所需的内容:

library(ggplot2)

dfx1$Week <- factor(dfx1$Week, ordered = T)

ggplot(dfx1, aes(Week, percent, col = Year, group = Year)) +
  geom_line() +
  facet_wrap(~Cty, 2, scales = 'fixed')

enter image description here

使用您的最后一行,您似乎只想显示实际拥有数据的Week。您可以使用scales = 'free'执行此操作,如下所示:

ggplot(dfx1, aes(Week, percent, col = Year, group = Year)) +
  geom_line() +
  facet_wrap(~Cty, 2, scales = 'free')

enter image description here