【问题标题】:Line graph customization (add circles, colors)折线图自定义(添加圆圈、颜色)
【发布时间】:2016-05-24 21:44:25
【问题描述】:

有数据

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("") 

我制作这个

但现在我想在下面创建类似的图片,其中 “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?

但没有运气。

如果上图无法做到这一点,我希望我的输出如下图所示

【问题讨论】:

    标签: r ggplot2


    【解决方案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" 一起使用,但是如果您只想要那些在相应方面具有值的名称,则这是必要的。

    【讨论】:

    • 感谢完美。你知道吗,我将如何添加或标记垂直组,即 PART1、PART2、PART3、PART4、PART5,就像在上一个帖子中发布的那样?
    • 就是这样。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 2015-02-17
    相关资源
    最近更新 更多