Home > Enterprise >  How do I create a categorical bar chart using ggplot2?
How do I create a categorical bar chart using ggplot2?

Time:10-31

I want to create a bar chart such that the x-axis contains the different engine_type and the y-axis contains the count. Data frame (DEU_2001_df) below:

   Year engine_type                count
1  2001 petrol_number           2185247 
2  2001 diesel_gas_number       1155300 
3  2001 full_mild_hybrid_number     606.
4  2001 plugin_hybrid_number          0 
5  2001 battery_electric_number      56 

When using the following line:

ggplot(DEU_2001_df, mapping = aes(x = 'engine_type', y = 'count'))  
  geom_bar(stat = "identity")

I get this plot: enter image description here

Steps taken as above.

CodePudding user response:

With your count values it will be hard to see battery_electric_number, full_mild_hybrid_number. Here is suggestion using the log of count

df %>% 
  mutate(count = as.numeric(count)) %>% 
  ggplot(aes(x = fct_reorder(engine_type, count), y = log(count))) 
  geom_col(fill = "maroon")  
  labs(title = "log of count", x = "Engine type")   
  theme_bw()   
  theme(axis.text.x=element_text(angle = -45, hjust = 0)) 

enter image description here

CodePudding user response:

Use variable name without inverted commas:

engine %>% ggplot(aes(x = engine_type, y = count)) geom_bar(stat = 'identity')

  • Related