Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use ggplot() to create this plot?

Tags:

r

ggplot2

This is my data frame:

library(ggplot2)
Year <- c(2019,2018,2017,2016,2015)
googlerev <- c(161857,136819,110855,90272,74989)
ibmrev <- c(77147,79591,79139,79919,81741)
df <- data.frame(Year, googlerev, ibmrev)
df
#>   Year googlerev ibmrev
#> 1 2019    161857  77147
#> 2 2018    136819  79591
#> 3 2017    110855  79139
#> 4 2016     90272  79919
#> 5 2015     74989  81741

How can I make a plot as shown in the picture below: enter image description here

(Revenue represents the value of google rev and ibmrev).

like image 648
Chris Avatar asked Aug 01 '26 08:08

Chris


2 Answers

We can use pivot_longer from the tidyr package to change your data, then use geom_col:

library(tidyr) 

df %>%
    pivot_longer(cols = -Year, names_to = "company", values_to = "revenue") %>%
    ggplot(aes(Year, revenue, fill = company))+
    geom_col(position = 'dodge')

enter image description here

like image 164
bouncyball Avatar answered Aug 03 '26 01:08

bouncyball


This will be easier with long formatted data to control ggplot behavior. You can use reshape2 package for that.

library(ggplot2)
df <- reshape2::melt(df, id.vars = "Year")

ggplot(df, aes(x = Year, y = value, fill = variable)) +
   geom_bar(stat = "identity", position = "dodge") +
   labs(x = "Year", y = "Revenue") 
like image 44
linog Avatar answered Aug 03 '26 01:08

linog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!