简体   繁体   English

r: ggplot2 条形图显示 Y 轴刻度乱序

[英]r: ggplot2 bar chart displaying Y-axis ticks out of order

I am plotting a multiple grouping bar chart and finding that, although the data is displaying correctly, the chart is completely skewed in it's display because the y-axis tick values are not in numerical order.我正在绘制一个多分组条形图并发现,虽然数据显示正确,但图表在其显示中完全倾斜,因为 y 轴刻度值不是按数字顺序排列的。

Current graph output:当前图形输出:

在此处输入图片说明

Below is my code, can anyone show me how I can order the values numerically?下面是我的代码,谁能告诉我如何按数字顺序排列值?

     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

Here is the output of my total_veg dataframe:这是我的 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

Value was a factor rather than numeric (discovered this via str() function). 值是一个因素,而不是数字(通过str()函数发现了这一点)。

I used as.numeric(as.character()) to convert value from factor to numeric, which then displayed the data in a meaningful order when plotted. 我使用as.numeric(as.character())将值从因子转换为数字,然后在绘制时以有意义的顺序显示数据。 Thanks to @MrFlick for pointing me in the right direction. 感谢@MrFlick为我指出正确的方向。

I encountered the same issue.我遇到了同样的问题。

The file that you uploaded might have had that column as a string some value(mine was currency and it had $ in the beginning).您上传的文件可能将该列作为某个值的字符串(我的是货币,开头是 $)。 Hence it was disordered.于是就乱了。

Either re-upload the data in the right format or change it to a numeric value and you would get it plotted right.要么以正确的格式重新上传数据,要么将其更改为数值,然后您就会将其绘制正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM