R:ggplot改变标签的顺序

时间:2014-04-29 13:22:58

标签: r plot ggplot2

我在使用ggplot时遇到了一些问题。我想要做的是绘制一个普通的boxplot图形和一些表格下面。

这里我将表的值定义为.df:

lab.df<-data.frame(lab1=c("0-12.9","13.0-19.2","19.3-23.2","23.3-26.3","26.4-29.8","29.9-33","33.1-36.5","36.6-40.8","40.9-46.2","46.3-100"),
lab2=c("7.80","16.62","21.29","24.71","28.12","31.40","34.80","38.60","43.22","53.77"),
lab3=c("58.63","46.03","46.68","48.84","51.92","54.11","56.50","59.71","62.41","68.33"))

在这里我创建并保存表格nr。 2:

df.table2 <- ggplot(lab.df, aes(x = lab2, y = 0,
                                label = lab2)) +
  geom_text(size = 5, colour = "black") + 
  theme_minimal() + 
  scale_y_continuous(breaks=NULL, name = "Mittelwert Parteistärke (%)")+
  theme(panel.grid.major = element_blank(), legend.position = "none",
        panel.border = element_blank(), axis.text.x =  element_blank(),
        axis.ticks =  element_blank(),
        axis.title.x=element_blank(),
        axis.title.y=element_text(angle = 0, hjust = 2.9))

现在,当我在ggplot中使用grid.arrange中的表时,值的顺序会发生变化。当我使用

绘制表格时会发生同样的情况
plot(df.table2)

价值观从“改变” 的 7.80 下,16.62,21.29,24.71,28.12,31.40,34.80,38.60,43.22,53.77" 至 “16.62,21.29,24.71,28.12,31.40,34.80,38.60,43.22,53.77, 7.80

无论我如何更改订单,7.80总是在最后而不是在开头。我在监督什么?非常感谢你的帮助!

1 个答案:

答案 0 :(得分:0)

为什么您希望这些数字为factors而不是numerics?解决问题最简单的方法就是转换为numerics

lab.df$lab2 <- as.numeric(as.character(lab.df$lab2))

如果您确实需要有因子,则需要指定所需的顺序。否则订单只是按字母顺序排列,而7.8是在53.77之后。

lab.df$lab2 <- factor(lab.df$lab2, levels=lab.df$lab2)