如何添加x轴标签ggplot2 r

时间:2016-06-23 07:41:18

标签: r ggplot2 bar-chart axis-labels

我想在ggplot条形图X轴上放一些标签。

数据:

var.A <- as.numeric(c(1:13))
var.B <- c(4.351833, 2.938000, 4.726465, 3.747162, 3.720737, 4.297117, 4.304500, 4.061277, 4.595236, 4.105444, 3.701684, 3.523563, 4.170000)
df <- data.frame(var.A,var.B)

ggplot代码:

ggplot(df, aes(x=var.A, y=var.B)) + 
  geom_bar(position=position_dodge(), stat="identity", fill="#fff68f", colour="darkgrey", width = 0.4) +
  coord_flip()+
  xlab("") +
  ylab("") +
  scale_x_discrete(labels=c("aaaaaaa aaaaa","bbbbb bbb bbbb","cccc ccc","dddd dd ddddd","eee e eeeee e ee","ffffffff","gggggggg","hhhhhhh","iiii","jjjjjj","kkkkkkk","llllll","mmmmmmmm"))

我指的是文档:ggplot documentation

如何强制R将此标签放在x-axxis上的位置?

1 个答案:

答案 0 :(得分:2)

您需要指定x作为因子。就是这样。

ggplot(df, aes(x=factor(var.A), y=var.B)) + 
  geom_bar(position=position_dodge(), stat="identity", fill="#fff68f", colour="darkgrey", width = 0.4) +
  xlab("") +
  ylab("") +
  scale_x_discrete(labels=c("aaaaaaa aaaaa","bbbbb bbb bbbb","cccc ccc","dddd dd ddddd","eee e eeeee e ee","ffffffff","gggggggg","hhhhhhh","iiii","jjjjjj","kkkkkkk","llllll","mmmmmmmm"))