Home > Blockchain >  how to make the positive value and negative value in same direction in ggplot2 bar chart
how to make the positive value and negative value in same direction in ggplot2 bar chart

Time:09-08

group = letters[1:10]
response = sample(-5:5, size=10, replace=TRUE)
df <- data.frame(group,
           response)

I want to make the figure like this figure wanted results to show the value of my research, but my data has both negative and positive values. I wonder how to change the y-axis to make them in the same direction. I tried to set the y-axis limits by scale_y_continuous() but it didn't work See My results. Thanks a lot for any possible solutions.

Here's my plotting code

ggplot(df)  
 aes(x = group, y = response, fill = response)  
 geom_col()  
 scale_fill_distiller(palette = "PiYG", 
 direction = 1)  
 theme_minimal()  
 theme(legend.position = "bottom") coord_polar()

CodePudding user response:

What about, instead of "response", mapping abs(response) to your y axis? I am assuming you want te colors to still reflect the original values, so you could keep fill mapped to "response".

Like so:

ggplot(df)  
 aes(x = group, y = abs(response), fill = response)  
 geom_col()  
 scale_fill_distiller(palette = "PiYG", 
 direction = 1)  
 theme_minimal()  
 theme(legend.position = "bottom") coord_polar()

CodePudding user response:

You could try using the abs(response) to generate absolute values for the y-axis. According to the desirable output you shared, you could also try reordering the groups using reorder(strwrap(x,10),y) to have ordered groups from that with the smallest response value to the largest. Additionally, I think theme_gray() with theme(legend.position = "right") completes the plot well. I have also added the following lines to properly label your axes:

Response = abs(response)#y-axis
Group = reorder(strwrap(group, 10), 
                Response)#x-axis

BTW, I'm new here, so please forgive me if my write-up and code is not well embedded :)

Here's my code:

library(ggplot2)
group = letters[1:10]
response = sample(-5:5, size=10, replace=TRUE)

df <- data.frame(group, response)

Response = abs(response)
Group = reorder(strwrap(group, 10), 
                Response)
ggplot(df)  
  aes(Group, Response, fill = response)  
  geom_col() 
  theme_gray() 
  scale_fill_distiller(palette = "PiYG", 
                      direction = 1)  
  theme(legend.position = "right") 
  coord_polar()

  • Related