Home > Blockchain >  How can I reshape the bar graph in R?
How can I reshape the bar graph in R?

Time:04-29

I want to resize the graph:

act_df %>%
ggplot(aes(x = Id, y = hours, fill = hour_type))  
geom_col(position = "fill")  
coord_flip()

because it looks like this: enter image description here

  1. An Id just expresses a person so it is not numeric. I want the vertical gaps between bars are same.

  2. The overall size should be larger than this.(especially horizontally)

How should I change this chart to make it more readable?

CodePudding user response:

Use width = argument. Here is an example:

mtcars %>%
  ggplot(aes(x = cyl, y = mpg, fill = am))  
  geom_col(position = "fill", width = 0.05)  
  coord_flip()

enter image description here

changing width in geom_col:

mtcars %>%
  ggplot(aes(x = cyl, y = mpg, fill = am))  
  geom_col(position = "fill", width = 1.5)  
  coord_flip()

enter image description here

CodePudding user response:

To give an example of making the Id column a factor on some simulated IDs:

library(tidyverse)

act_df <- tibble(
  Id = sample (10000:99999, 20),
  a = sample(1:10, 20, replace = TRUE),
  b = sample(1:10, 20, replace = TRUE),
  c = sample(1:10, 20, replace = TRUE),
  d = sample(1:10, 20, replace = TRUE)
) %>% 
  pivot_longer(-Id, names_to = "hour_type", values_to = "hours")

act_df %>%
  mutate(Id = as_factor(Id)) %>% 
  ggplot(aes(y = Id, x = hours, fill = hour_type))  
  geom_col(position = "fill")

Making it a factor, rather than an integer, tells R to 'ignore' the distance between each ID (i.e. stop treating it as a continuous variable) and plot each one labelled side by side.

For future reference - in this question and your other related question - it helps a lot to give some sample data using dput to be sure we're answering the right question. Simulating data (as I've done above) is one way of recreating a problem without using sensitive/restricted data.

Created on 2022-04-28 by the reprex package (v2.0.1)

  • Related