在 R 中两次反转 x 轴

Reverse x-axis two time in R

我想将 x 轴反转两次。现在我简单地反转了 x 轴的范围,我的结果是 3, 2, 1, 0 而不是 0, 1, 2, 3.

我的代码:

temp2 = table(mFT$Vorschlaege, mFT$Bewertung)

barplot(temp2 , main="10 Vorschläge pro Methode", xlab="Bewertung", beside=TRUE, ylim = c(0,40), xlim= c(43,3), col = colours10) 
legend("top", legend = rownames(temp2), fill = colours10)

现在我想将条形反转为 3、2、1 和 0。 "Vorschlag 1" 应该放在第一位,"Vorschlag10" 最后。

我该怎么做?

假设 mFT$Vorschlaege 是一个因子,您可以颠倒因子 levels.Try 的顺序:

mFT$Vorschlaege2 <- factor(mFT$Vorschlaege,levels = levels(mFT$Vorschlaege)[10:1])

这会颠倒您的因子水平的顺序。如果 mFT$Vorschlaege 不是一个因素,您必须先将其变成一个因素。我重命名了变量 mFT$Vorschlaege2 以避免覆盖您的原始变量,因此您必须使用新变量重复 table 命令。

temp2 = table(mFT$Vorschlaege2, mFT$Bewertung)
    barplot(temp2 , main="10 Vorschläge pro Methode", xlab="Bewertung", beside=TRUE, ylim = c(0,40), xlim= c(43,3), col = colours10) 
    legend("top", legend = rownames(temp2), fill = colours10)

没有可重现的示例,我无法测试此解决方案,但它适用于我自己的数据。

是的,因素是这里的关键。 我使用玩具数据集用 ggplot2 创建了一个条形图:

library(ggplot2)

### toy dataset
Vorschlaege <- c("V1", "V3", "V2", "V5", "V4")
Bewertung <- c(100, 20, 30, 40, 50)
df <- data.frame(Vorschlaege, Bewertung)

## define sorting order by factor as you want to have it in your bar chart:
df$Vorschlaege <- factor(df$Vorschlaege, levels = c("V5", "V4", "V3", "V2", "V1"))

ggplot(df, aes(df$Vorschlaege)) + 
  geom_bar(aes(weight = df$Bewertung)) +
  labs(title = "Meine Vorschläge",
       x = "Vorschlag", y = "Bewertung",
       subtitle = "Zeitraum: x bis y", caption = "Quelle: Meine Forschung") +
  theme_bw() ## white background theme