ggplot图-重新排序变量并更改线的粗细/颜色

时间:2018-11-10 07:51:24

标签: r ggplot2

这段代码创建了一个基本图,但是我不知道如何按值顺序对值进行排序(已包含fct_reorder,但我一定做错了)。我还想给线条上色并使其更粗。

library(tidyverse)
dat2 <- tibble(Percentage = c(12.5,58.9,9.1,3.6,7.3,7.3),
               ICDDx = c("Dx1","Dx2","Dx3","Dx4","Dx5","Dx6"))

library(ggplot2)
ggplot(dat2, aes(Percentage,ICDDx, fct_reorder(Percentage))) +
  geom_segment(aes(x = 0, y = ICDDx, xend = Percentage,  
                   yend = ICDDx), color = "grey50") +  
  geom_point(size=6)

我尝试指定geom_line(size = 3),但收到此错误:

Error: `data` must be a data frame, or other object coercible by 
`fortify()`, not an S3 object with class LayerInstance/Layer/ggproto/gg

3 个答案:

答案 0 :(得分:2)

只需使用geom_lollipop()

library(tidyverse)

dat2 <- tibble(Percentage = c(12.5,58.9,9.1,3.6,7.3,7.3),
               ICDDx = c("Dx1","Dx2","Dx3","Dx4","Dx5","Dx6"))

mutate(dat2, ICDDx = fct_reorder(ICDDx, Percentage)) %>% 
  mutate(Percentage = Percentage/100) %>% 
  ggplot() +
  ggalt::geom_lollipop(
    aes(Percentage, ICDDx), horizontal=TRUE,
    colour = "#6a3d9a", size = 2,
    point.colour = "#ff7f00", point.size = 4
  ) +
  hrbrthemes::scale_x_percent(
    expand=c(0,0.01), position = "top", limits = c(0,0.6)
  ) +
  labs(
    x = NULL, y = NULL
  ) +
  hrbrthemes::theme_ipsum_rc(grid="X")

enter image description here

答案 1 :(得分:0)

这是我对您问题的解释的答案。

node_modules/.bin

给出以下图:

enter image description here

答案 2 :(得分:0)

您可以先进行排名。

dat2 <- dat2[order(dat2$Percentage), ]  # order by percentage
dat2$rank <- 1:nrow(dat2)  # add ranking variable

ggplot(dat2, aes(x=Percentage, y=rank, group=rank, color=ICDDx)) +
  geom_segment(aes(x=0, y=rank, xend=Percentage,  
                   yend=rank), col="grey50", size=2) +  
  geom_point(size=6) +
  scale_y_continuous(breaks=1:length(dat2$ICDDx), labels=dat2$ICDDx) +  # optional
  scale_color_discrete(labels=dat2$ICDDx)

屈服

enter image description here