ggplot具有所有x轴值的x轴标签 [英] ggplot x-axis labels with all x-axis values

查看:364
本文介绍了ggplot具有所有x轴值的x轴标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用geom_point绘制ggplot. x轴将是个人的ID,y轴是变量A.如何在不重叠标签的情况下在x轴上绘制所有ID值和个人ID值? ID可能不是连续的.

I'm plotting ggplot with geom_point. The x-axis will be individuals' ID, and y-axis is variable A. How can I ggplot all and individual ID values on the x-axis without overlapping labels? ID may not be continuous.

df样本(实际行更长)

df sample (actual rows are much longer)

> df
ID     A
1      4
2      12
3      45
5      1

剧情代码:

ggplot(df, aes(x = ID, y = A)) + geom_point()

以上代码的间隔为x轴,但未显示单个ID.

Above code has x-axis in intervals, but not presenting individual ID.

谢谢!

推荐答案

这是您要寻找的吗?

ID <- 1:50
A <- runif(50,1,100)

df <- data.frame(ID,A)

ggplot(df, aes(x = ID, y = A)) + 
  geom_point() + 
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
  scale_x_continuous("ID", labels = as.character(ID), breaks = ID)

这将产生此图像:

因此,您将获得每个ID值的标签.如果要删除网格线(我的口味太多),可以通过添加theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

So you'll get a label for every ID-value. If you'd like to remove the gridlines (There are too much for my taste) you can remove them by adding theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

编辑:更简单的方法是将ID用作绘图的一个因素.像这样:

The easier way would be to just use ID as a factor for the plot. like this:

ggplot(df, aes(x = factor(ID), y = A)) + 
  geom_point() + 
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
  xlab("ID")

此方法的优点是您不会从丢失的ID中获得空白

The advantage of this method is that you don't get empty spaces from missing IDs

EDIT2 :关于标签重叠的问题:我猜想它来自大量要绘制的ID.我们可以通过几种方法来解决这个问题.因此,假设您的情节看起来像这样:

Concerning your Problem with overlapping labels: I'm guessing it comes from a large number of IDs to be plotted. There are several ways we can deal with this. So lets say your plot looks like this:

一个想法是通过修改轴的break参数来隐藏x轴上的每个第3个标签:

One idea would be to hide every 3rd label from the x-axis by modifying the break argument of the axis:

ggplot(df, aes(x = factor(ID), y = A)) + 
  geom_point() + 
  scale_x_discrete(breaks = ID[c(T,F,F)]) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
  xlab("ID")

这导致了这一点:

如果不选择隐藏标签,则可以将图分成多个子图.

If hiding labels is not an option, you could split your plot into subplots.

df$group <- as.numeric(cut(df$ID, 4))

ggplot(df, aes(x = factor(ID), y = A)) + 
  geom_point() + 
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
  xlab("ID") +
  facet_wrap(~group, ncol = 1, scales = "free_x")

这导致了这一点:

这篇关于ggplot具有所有x轴值的x轴标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆