ggplot中的多行和条形图,带有geom_text和颜色

时间:2015-10-22 11:43:01

标签: r charts ggplot2

我想使用ggplot将线条和条形图与三个不同的变量结合起来。条形图应该具有顶部的值,并且应该使用与上图中的线相同的颜色填充。这是我的代码

# First some data generation
df.x = data.frame(date = Sys.Date()-20:1,
                  value = c(1:20),
                  variable = "line",
                  object = "x")

df.y = data.frame(date = Sys.Date()-20:1,
                  value = c(1:20)*2,
                  variable = "line",
                  object = "y")

df.z = data.frame(date = Sys.Date()-20:1,
                  value = c(1:20)*3,
                  variable = "line",
                  object = "z")

df.y.bar = data.frame(date = Sys.Date()-10,
                  value = 30,
                  variable = "bar",
                  object = "y")

df.x.bar = data.frame(date = Sys.Date()-10,
                      value = 40,
                      variable = "bar",
                      object = "x")

df.z.bar = data.frame(date = Sys.Date()-10,
                      value = 50,
                      variable = "bar",
                      object = "z")

df = rbind(df.x, df.y,df.z, df.x.bar, df.y.bar,df.z.bar)

my.cols = c("blue", "green", "yellow")

# Pass everything to ggplot
ggplot(df, aes_string(x = "date", y = "value", fill="variable")) +  
  facet_grid(variable~., scales="free_y") + 
  geom_line(data = subset(df, variable == "line"), aes(colour = factor(object)), size = 1, show_guide = FALSE, stat="identity") +
  geom_bar(data = subset(df, variable == "bar"), aes(colour = factor(object)), show_guide = TRUE, stat="identity", position = "dodge") +
  geom_text(data = subset(df, variable == "bar"), aes(y=value+0.7 * sign(value), ymax=value, label=round(value, 2)), position = position_dodge(width = 0.9), size=3) + 
  scale_colour_manual(values = my.cols)

结果情节并不完全是我想要的。我使用position_dodge(width = 0.9)但是栏上的文字没有移动。令人遗憾的是,当我只选择两个变量(例如x和y)包含在数据帧中时,这不会发生。期望的结果应如下所示:

enter image description here

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:2)

您可以选择fill = factor(object)并添加scale_fill_manual(values = my.cols)来填充栏。 为了只有一个图例,我认为从fill="variable"删除aes_string可以与scale_fill_manual结合使用。 为了避开文本,您需要添加group参数和position = position_dodge(width=1)

ggplot(df, aes_string(x = "date", y = "value")) +  
          facet_grid(variable~., scales="free_y") + 
          geom_line(data = subset(df, variable == "line"), aes(colour = factor(object)), size = 1, show_guide = FALSE, stat="identity") +
          geom_bar(data = subset(df, variable == "bar"), aes(fill = factor(object)), show_guide = TRUE, stat="identity", position = "dodge") +
          geom_text(data =subset(df, variable == "bar"), aes(x=date, y=(value+0.7) * sign(value), ymax=value, label=round(value, 2), group=object), position = position_dodge(width=1), size=3) +
          scale_colour_manual(values = my.cols) +
          scale_fill_manual(values = my.cols)

enter image description here