简体   繁体   中英

How to plot bar chart grouped by secondary variable in R?

I have a dataset with a set of KPIs for each year:

在此处输入图片说明

Using RI want to plot the KPIs in a bar chart in such a way that the bars are grouped by KPIs like this:

在此处输入图片说明 The above chart is very easy to obtain in Excel, but I am struggling to achieve the same result in R using ggplot2 library. This is my attempt:

    coeffs <- read.csv("all_coefficients.csv")

ggplot(data = coeffs %>% gather(Variable, Coefficient, -year), 
       aes(x = year, y = Coefficient, fill = Variable)) + 
    geom_bar(stat = 'identity', position = 'dodge') +
  theme(legend.position="bottom")

but the output is:

在此处输入图片说明

How can I group the bars by KPIs and not by year and assign a different colour to each year's bar?

Changing to

aes(x = Variable, y = Coefficient, fill = factor(year))

should give you what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM