Rémi Pts
Rémi Pts

Reputation: 59

GGPLOT order of variable

I have a barplot produced in ggplot. The order of appearance in the legend is totally ok, but does not correspond to the order of the bars in the graph.

Here is the code to produce the graph :

library(reshape2)
library(ggplot2)

benchmarkDim <- c("x", "Media", "Souvenir brut", "Attribution marque", "Souvenir net marque")
benchmarkTV <- c("Benchmark TV Telco", "TV", "53", "69", "36")
benchmarkRadio <- c("Benchmark RADIO Telco", "Radio", "38", "55", "21")
benchmarkPresse <- c("Benchmark PRESSE Telco", "Presse", "30", "64", "19")
benchmarkAffichage <- c("Benchmark AFFICHAGE Telco", "Affichage", "35", "66", "23")
benchmarkOnline <- c("Benchmark ONLINE Telco", "Online", "35", "68", "24")
benchmarkTTB <- c("Benchmark TTB Monitor", "TTB", "23", "82", "19")
benchmarkData <- data.frame()
benchmarkData <- data.frame(rbind(benchmarkTV, benchmarkRadio, benchmarkPresse, benchmarkAffichage, benchmarkOnline, benchmarkTTB))
colnames(benchmarkData) <- benchmarkDim
rownames(benchmarkData) <- c()

postTestsDim <- c("x", "Media", "Souvenir brut", "Attribution marque", "Souvenir net marque")
mesure1 <- c("Test", "TV", 99, 80, 55)
mesure2 <- c("Test2", "radio", 45, 65, 90)
mesureData <- data.frame()
mesureData <- data.frame(rbind(postTestsDim, mesure1, mesure2))
colnames(mesureData) <- postTestsDim
rownames(mesureData) <- c()

finalData <- data.frame(rbind(benchmarkData, mesureData))
finalData <- finalData[-c(1,2,3,4,5,7),]
finalData$Media <- NULL

finalData <- melt(finalData, id.vars = "x")

finalData$c <- as.factor(ifelse(grepl('Benchmark', finalData$x), 1, 2))
finalData$variable <- as.factor(finalData$variable)
finalData$int <- interaction(finalData$c, finalData$variable)

ggplot(finalData, aes(x = finalData$x, y = finalData$value, fill = finalData$int)) + 
  geom_bar(stat = "identity", position = "dodge") + 
  scale_fill_manual(values = c("#4F81BD", "#EF1D9A", "#8DB4E3", "#f456B4", "#1F497D", "#FAB4DE")) +
  theme_minimal()

Basically, it looks like the plot shows the bars based on the smallest value to the highest one. It should display the bars based on the order of the legend.

I'm open to every idea.

Best,

Rémi

Upvotes: 0

Views: 156

Answers (1)

moodymudskipper
moodymudskipper

Reputation: 47350

You need to be explicit about your groups, for some reason defining groups implicitly through the fill argument ignores the levels order :

ggplot(finalData, aes(x = finalData$x, y = finalData$value, fill = finalData$int,
                      group = finalData$int)) + 
  geom_bar(stat = "identity", position = "dodge") + 
  scale_fill_manual(values = c("#4F81BD", "#EF1D9A", "#8DB4E3", "#f456B4", "#1F497D", "#FAB4DE")) +
  theme_minimal()

Upvotes: 1

Related Questions