在geom_point中具有多种颜色的比例尺

时间:2019-05-15 14:24:21

标签: r ggplot2

我有类似的数据框

dt = data.frame("a" =c(1,2,3,4,5,6,7), "b" =c(0,1,1,2,0,3,1))

我想创建一个类似的图(它是手工制作的,所以会有一些错误,但是重点是我想将所有气泡都用颜色编码显示在一行上)

enter image description here

尽管muy当前代码在x轴上放置了所有可能的4个值,并在每个刻度上显示了点

    p1<-ggplot(dt, aes(x = factor(a, levels = a), y = b, fill= b)) + 
  geom_point(stat='identity', size = 6, aes(col=b))  +
  theme(axis.text.x = element_text(angle=90, vjust=0.6,size = 25),
        axis.text.y = element_text(size = 25)) +
        coord_flip()

上面的代码产生以下输出

enter image description here

1 个答案:

答案 0 :(得分:1)

根据您的输出示例,您只需要使用相同的x(例如x=1), 并删除标签:

dat = data.frame("a" =c(1,2,3,4,5,6,7), "b" =c(0,1,1,2,0,3,1))

library(ggplot2)

ggplot(dat, aes(x=1, y=a, color=as.factor(b))) + # b will control the color groups
  geom_point(size=6, shape=19) +
  scale_y_continuous(breaks=seq(min(dat$a), max(dat$a), by = 1)) + # in order to print each y labels
  theme_minimal() +
  theme(axis.text.x = element_blank(), # element_blank() removes the element
        axis.title.x = element_blank(), # title refers to the title of axis
        axis.title.y = element_blank(),
        legend.position = "none") # this removes the legend

enter image description here

如果要反转y轴的顺序,请使用scale_y_reverse()

ggplot(dat, aes(x=1, y=a, color=as.factor(b))) + 
  geom_point(size=6, shape=19) +
  scale_y_reverse(breaks=seq(min(dat$a), max(dat$a), by = 1)) +
  theme_minimal() +
  theme(axis.text.x = element_blank(),
        axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        legend.position = "none")

enter image description here

如果要缩小范围,请使用aspect.ratio

ggplot(dat, aes(x=1, y=a, color=as.factor(b))) + 
  geom_point(size=6, shape=19) +
  scale_y_reverse(breaks=seq(min(dat$a), max(dat$a), by = 1)) +
  theme_minimal() +
  theme(axis.text.x = element_blank(),
        axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        legend.position = "none",
        aspect.ratio = 3)

enter image description here


您可以基于reorder(),使用yb值将它们“聚集”在一起(注意,您将失去y轴的自然顺序):

ggplot(dat, aes(x=1, y=reorder(a, b), color=as.factor(b))) + 
  geom_point(size=6, shape=19) +
  theme_minimal() +
  theme(axis.text.x = element_blank(),
        axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        legend.position = "none",
        aspect.ratio = 3)

enter image description here