-2

I have this data:

Year    A    B      C       D       E
Y2000   6.8  5.3    36.7    41      10.2
Y2001   2   10.6    40.3    37.8    9.3
Y2002   2.2  8.8    38      40.6    10.5
Y2003   2.3 14.2    41.6    33.8    8.1
Y2004   2.9  6.8    42.3    38.3    9.7
Y2005   5.5 11.9    39.1    43.4    NA
Y2006   6.4  8.6    32.4    41.1    11.4
Y2007   7.7 13.7    29.6    38.9    10
Y2008   9   10.4    36.5    38.8    5.2
Y2009   NA    NA    50.9    49.1    NA

and code

attach(Data)
mydata <- factor(format(seq(as.Date('2020-01-01'), length.out=10, by='1 year'),'%Y'),
                 levels = format(seq(as.Date('2020-01-01'), length.out=10, by='1 year'),'%Y'),
                 ordered = T)

colnames(Data) <- c("A", "B", "C", "D", "E")

library(ggplot2)
library(reshape2)
xym <- melt(mydata)

ggplot(xym, aes(x = Data$Year, y = value)) +
      theme_bw() +
      scale_fill_brewer(palette = "Set1") + 
      theme(legend.position = "right", axis.text.x = element_text(angle = 90,vjust = 0.2)) +
      geom_bar(stat = "identity", position = "dodge") +
      geom_bar(fill = c("green", "blue", "red", "yellow", "black")))

I am struggling to get the plot that I want. It should be similar to the plots in this question: Barplot customization

Edo
  • 7,567
  • 2
  • 9
  • 19
  • Hi, please comply [how-to-make-a-great-r-reproducible-example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610). – jay.sf Aug 20 '20 at 09:28
  • what's the purpose of `xym`? – Edo Aug 20 '20 at 10:00

1 Answers1

0

This is how you get a similar barplot to the one you linked. I left all the settings you set up in your example.

library(ggplot2)
library(tidyr)

Data <- tibble::tribble(
    ~Year,    ~A,    ~B,      ~C,       ~D,       ~E,
    "Y2000",   6.8,  5.3,    36.7,    41,      10.2,
    "Y2001",   2,   10.6,    40.3,    37.8,    9.3,
    "Y2002",   2.2,  8.8,    38,      40.6,    10.5,
    "Y2003",   2.3, 14.2,    41.6,    33.8,    8.1,
    "Y2004",   2.9,  6.8,    42.3,    38.3,    9.7,
    "Y2005",   5.5, 11.9,    39.1,    43.4,    NA,
    "Y2006",   6.4,  8.6,    32.4,    41.1,    11.4,
    "Y2007",   7.7, 13.7,    29.6,    38.9,    10,
    "Y2008",   9,   10.4,    36.5,    38.8,    5.2,
    "Y2009",   NA,    NA,    50.9,    49.1,    NA
)


Data %>%
    pivot_longer(-Year) %>% 
    
    ggplot(aes(x = Year, y = value, fill = name)) +
    geom_bar(stat = "identity", position = "dodge") +
    theme_bw() +
    scale_fill_brewer(palette = "Set1") + 
    theme(legend.position = "right", axis.text.x = element_text(angle = 90,vjust = 0.2))

enter image description here I don't know if you want to copy the labels too.

Edo
  • 7,567
  • 2
  • 9
  • 19