如何在ggplot2中放入大量x标签或空格x标签

时间:2018-06-13 21:56:30

标签: r ggplot2

有没有办法摆出空间,以便每个x标签更具辨别力? 我觉得之前已经问过这个问题,但我似乎无法找到答案。我相信这个图需要更大才能工作,是否可以让Rstudio中的图形更大?或使文字变小

到目前为止我的代码:

bar_plt = ggplot(data, aes(fct_infreq(Event))) + geom_bar(fill = "dodgerblue", width = .4) +
                 xlab("Event Names") + ylab("Number of Observations") + coord_flip() 

TIA

is there a way to space out the x label so it is more distinguishable?

1 个答案:

答案 0 :(得分:2)

用这种方式处理标签怎么样(对于假数据很抱歉,但我还没有你的样本):

library(ggplot2)
# numbers
set.seed(1)
y<-sample(1:30, 500, TRUE)

# very long and numerous labels
x <-  paste(sample(letters[1:22], 500, TRUE),sample(letters[1:2], 500, TRUE),'abcdefghijklmnopqrstuvwxyz')
data <- data.frame(x,y)

# simple ggplot barplot
p <- ggplot(data, aes(x = x, y = y)) + geom_bar(stat = "identity") + coord_flip()

# play with the size to have a fitting dimension
p <- p + theme(axis.text.y = element_text(face="bold", color="black",  size=8))

# you can also abbreviate the labels if necessary
p <- p + scale_x_discrete(labels = abbreviate)
p

你的情节可能是这样的:

library(forcats)
library(ggplot2)

# data
set.seed(1)
Events <-  paste(sample(letters[1:22], 500, TRUE),sample(letters[1:2], 500, TRUE),'abcdefghijklmnopqrstuvwxyz')
data <- data.frame(Events)

bar_plt <- ggplot(data, aes(fct_infreq(Events))) + geom_bar(fill = "dodgerblue", width = .4) + coord_flip()
bar_plt <- bar_plt + xlab("Event Names") + ylab("Number of Observations")
bar_plt <- bar_plt + theme(axis.text.y = element_text(face="bold", color="black",  size=8))
bar_plt <- bar_plt + scale_x_discrete(labels = abbreviate)
bar_plt

enter image description here