r:ggplot2条形图显示Y轴顺序错误

时间:2015-05-20 18:38:36

标签: r ggplot2

我正在绘制一个多分组条形图,并发现尽管数据显示正确,但图表在显示中完全偏斜,因为y轴刻度值不是按数字顺序排列的。

当前图表输出:

enter image description here

以下是我的代码,有人能告诉我如何以数字方式订购数值吗?

     library(ggplot2)
veg_db <- read.csv("filepath\\filename.csv", header = TRUE)
veg_df <- data.frame(veg_db)

veg <- veg_df[c(125),c(4,5,9,12,13,18)]
white_veg <- data.frame(t(veg))
colnames(white_veg) <- c("value")
rownames(white_veg) <- c("Broccoli", "Carrots", "Leafy Greens", "Peas", "Peppers", "Tomatoes")
white_veg <- cbind(vegetables = rownames(white_veg),ethnicity = "white", white_veg)


veg <- veg_df[c(129),c(4,5,9,12,13,18)]
black_veg <- data.frame(t(veg))
colnames(black_veg) <- c("value")
rownames(black_veg) <- c("Broccoli", "Carrots", "Leafy Greens", "Peas", "Peppers", "Tomatoes")
black_veg <- cbind(vegetables = rownames(black_veg),ethnicity = "black", black_veg)

total_veg <- merge(white_veg, black_veg, all = TRUE)
total_veg

plot <- ggplot(total_veg, aes(vegetables, value, fill = ethnicity))+
  geom_bar(position="dodge",stat="identity")


plot

以下是我的total_veg数据框的输出:

  

total_veg

     vegetables ethnicity value
1      Broccoli     white 10.18
2      Broccoli     black  6.46
3       Carrots     white 12.58
4       Carrots     black  8.54
5  Leafy Greens     white  2.88
6  Leafy Greens     black  1.68
7          Peas     white 19.96
8          Peas     black 13.13
9       Peppers     white  3.09
10      Peppers     black  3.12
11     Tomatoes     white 80.13
12     Tomatoes     black 62.08

1 个答案:

答案 0 :(得分:0)

值是一个因素而不是数字(通过str()函数发现)。

我使用as.numeric(as.character())将值从因子转换为数字,然后在绘制时以有意义的顺序显示数据。感谢@MrFlick指出我正确的方向。