如何在x轴上拆分字符并为其指定颜色

时间:2017-01-22 07:26:06

标签: r ggplot2 split

我是R和ggplot2的新手。目前我有一个这样的情节:

http://imgur.com/lJFXVfZ.png

我想要那样的东西:

http://imgur.com/czXg0Yb.png

不幸的是,我不知道如何在x轴上分割字符并为它们分配不同的颜色。

这是我的代码:

attach(trustData)

ag <- aggregate(trustData, by = list(type = face_category_and_gender2_ZAUFANIE), mean)

plot <- ggplot(data = ag, aes(x = type, y = response)) + list(geom_point(colour = 'red'))

plot

作为新成员,我不能在这里放置超过2个链接,因此已汇总数据的示例在评论中

谢谢!

1 个答案:

答案 0 :(得分:0)

我们可以separate&#39;类型&#39;列,然后进行绘图

library(dplyr)
library(tidyr)
library(ggplot2)
ag %>% 
    separate(type, into = c("val", "Type"), "(?=[A-Z])", remove = FALSE) %>%
    mutate(val = factor(val, levels = sort(unique(as.numeric(val)))),
            Type = factor(Type, levels =c("M", "K"), labels = c("Men", "Woman"))) %>%
    ggplot(., aes(x = val, y = response, col = Type)) + 
                geom_point()

或者代替factor使用case_when

中的dplyr
ag %>%
   separate(type, into = c("val", "Type"), "(?=[A-Z])", remove = FALSE) %>% 
   mutate(val = factor(val, levels = sort(unique(as.numeric(val)))),
          Type = case_when(.$Type == "M" ~ "Men", TRUE ~ "Woman")) %>%
   ggplot(., aes(x = val, y = response, col = Type)) + 
                geom_point()

enter image description here

数据

ag <- structure(list(type = c("12K", "12M", "15K", "15M", "1K", "1M", 
"4K", "4M", "7K", "7M", "9K", "9M"), response = c(41.83, 42.45, 
40.61, 40.69, 64.59, 57.88, 61.2, 54.71, 49.23, 48.24, 44.27, 
45.09)), .Names = c("type", "response"), row.names = c(NA, -12L
), class = "data.frame")