Reputation: 923
I have a dataframe shown below:
structure(list(Age_group = c("0-1", "16-40", "2-5", "6-15", "Others"
), Ratio_no_V_tour = c(0.144814506265842, 0.368098268252477,
0.135597426307673, 0.291277451831895, 0.0602123473421132), Ratio_V_tour = c(0.0704375667022412,
0.431100508506498, 0.12103710214075, 0.302278862452131, 0.0751459601983803
)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"
))
Age_group Ratio_no_V_tour Ratio_V_tour
<chr> <dbl> <dbl>
1 0-1 0.145 0.0704
2 16-40 0.368 0.431
3 2-5 0.136 0.121
4 6-15 0.291 0.302
5 Others 0.0602 0.0751
I am wodnering how I can plot a bar plot for column Ratio_no_V_tour and Ratio_V_tour for each Age_group. I looked into some solutions like this one https://dk81.github.io/dkmathstats_site/rvisual-sidebyside-bar.html ; however, in the example shown in the link, the two-column has the same name. I can do the same here manually, but I am more looking into smarter solution to plot this
Upvotes: 1
Views: 2391
Reputation: 887118
We may use base R
barplot
barplot(t(`row.names<-`(as.matrix(df1[-1]), df1$Age_group)),
legend = TRUE, beside = TRUE)
-output
Or if we wanted to use ggplot
, reshape to 'long' format
library(ggplot2)
library(dplyr)
library(tidyr)
df1 %>%
pivot_longer(cols = -Age_group) %>%
ggplot(aes(x = Age_group, y = value, fill = name)) +
geom_col(position = 'dodge') +
theme_bw()
-output
Upvotes: 2