bgreen
bgreen

Reputation: 87

ggplot plot - reorder variable & alter line thickness/colour

This code creates a basic plot but I can't work out how to order the values in order of value (fct_reorder is included but I must have done something wrong). I also wanted to colour the lines and make them thicker.

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)

I tried to specify geom_line(size = 3), but received this error:

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

Upvotes: 0

Views: 168

Answers (3)

hrbrmstr
hrbrmstr

Reputation: 78842

Just use 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

Upvotes: 2

jay.sf
jay.sf

Reputation: 73802

You could do a ranking first.

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)

Yielding

enter image description here

Upvotes: 0

NelsonGon
NelsonGon

Reputation: 13319

Here is my answer based on my interpretation of your question.

     dat2 %>% 
  arrange(Percentage) %>% 
  ggplot(aes(Percentage,ICDDx,col=ICDDx,size=4))+ 
  geom_segment(aes(x = 0, y = ICDDx, xend = Percentage, yend = ICDDx))+  
  geom_point(size=6)

That gives the following plot:

enter image description here

Upvotes: 0

Related Questions