GGPLOT变量的顺序

时间:2019-03-21 11:04:28

标签: r ggplot2

我在ggplot中生成了一个barplot。图例中的出现顺序完全可以,但是与图中的条形顺序不符。

以下是生成图形的代码:

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()

基本上,该图显示出基于最小值到最大值的条形图。它应该根据图例的顺序显示条形图。

我愿意接受所有想法。

最佳,

Rémi

1 个答案:

答案 0 :(得分:1)

您需要明确说明您的组,由于某些原因,通过fill参数隐式定义组会忽略级别顺序:

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()