线图自定义(添加圆圈,颜色)

时间:2016-05-24 21:44:25

标签: r ggplot2

使用数据

value <- c(9, 4, 10, 7, 10, 
           10, 10, 4, 10, 
           4, 10, 2, 5, 5, 4)

names  <-  c("a","b",
             "c","d","e",
             "f", "g","h",
             "i","j","k","l",
             "m","n","p")

df <- data.frame(value, names)
df$names <- as.character(df$names)

p <- ggplot(data = df, aes(y = value,x= names,group=1))+
  geom_point(color = I("red"),shape=23, lwd=3,fill="red")+
  geom_line(group = I(1),color = I("red"))+
  theme_bw()+
  coord_flip()
p + xlab("") +ylab("") 

我制作了这个

enter image description here

但是现在我想在下面创建类似图片,其中“a”,“b”,“c”和“D”将是x aes标签并且属于 PART 1 名称“p”,“n”,“m”,“i”,“k”属于第2部分(依此类推)。这里的关键部分是如何在剧情中添加圈子。

我也看过这里 How can I add freehand red circles to a ggplot2 graph?

但没有运气。

enter image description here

如果在上层时间不可能,那么我希望我的输出如下图所示

enter image description here

1 个答案:

答案 0 :(得分:1)

为了在上一个图中按部分实现构面,您可以创建一个新的列,对您的值进行分组,例如:

df$part <- rep(c("part3", "part2", "part1"), each = 5)

为了绘制空心圆圈,您可以添加另一个geom_point()图层。我创建了一个新数据框,其中包含每个部分namesvalue的所有组合:

library(dplyr)
library(tidyr)

df2 <- df %>% 
  group_by(part, names) %>% 
  expand(value = min(df$value):max(df$value))

然后用圆圈绘制一个刻面图:

ggplot() +
  geom_point(data = df2, aes(x = value, y = names),
             shape = 1) +
  geom_point(data = df, aes(y = names, x = value, group = 1), colour = I("red"), shape = 23, lwd = 3, fill = "red") +
  geom_line(data = df, aes(y = names, x = value, group = 1), group = I(1),color = I("red")) +
    theme_bw() +
  facet_wrap(~part, ncol = 1, scales = "free_y")

请注意,我交换了x和y值,因为coord_flip()不能与scales = "free_y"一起使用,但如果您只想要在相应方面具有值的名称,则必须使用这些值。

enter image description here