ggplot中x轴标签的所有x轴值

37

我用ggplotgeom_point绘制图表。X轴是个体的ID,Y轴是变量A。如何在x轴上绘制所有的个体ID值而不重叠标签?ID可能不连续。

数据框示例(实际行数要长得多)

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

绘图代码:

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

以上代码将x轴分成了区间,但没有显示个体ID。

谢谢!


假设您的ID名称非常长。旋转标签可能是个好主意?请参见:https://dev59.com/mnM_5IYBdhLWcg3wjj0p - Linus
3个回答

94

这是你在寻找的东西吗?

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)

这将生成此图像:

enter image description here

所以你会为每个ID值得到一个标签。如果您想删除网格线(对我来说太多了),可以通过添加theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())来删除它们。 编辑:更简单的方法是将ID直接用作绘图的因子,像这样:
ggplot(df, aes(x = factor(ID), y = A)) + 
  geom_point() + 
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
  xlab("ID")

enter image description here

这种方法的优点是,您不会因为缺少ID而获得空白空间。 编辑2: 关于标签重叠的问题:我猜这是由于要绘制的ID数量很大。我们可以用几种方法来解决这个问题。假设您的图表如下所示:

enter image description here

一种想法是通过修改坐标轴的break参数来隐藏x轴上每三个标签中的一个:

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")

这导致了这个结果:

enter image description here

如果不能隐藏标签,你可以将绘图分成多个子图。
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")

这导致了这个:

enter image description here


谢谢!那正是我需要的。请问如何像您在第二个图中所做的那样增加x轴标签之间的间距?我的标签重叠了。 - Lumos
1
为什么你的标签重叠了?我猜你试图绘制许多ID。我已经编辑了我的答案并添加了一些信息,如果我的想法适用于你,请告诉我。 - brettljausn
1
太棒了!我一直在到处寻找这样的东西! - mayrop

0
这对我来说很有效,当ID是离散和不连续的时候。
df$ID <- as.character(df$ID)
xlab <- sort(unique(df$ID))
ggplot(df, aes(x= ID, y= A)) + geom_point() + scale_x_discrete(labels= xlab)

-1

只需添加+ xlim()+ ylim()即可显示完整的x轴和y轴(即使x轴和y轴从零开始)。

可重现的示例

如果这是您的ggplot:

iris %>% 
  ggplot(aes(x=Sepal.Length, y=Sepal.Width)) +
  geom_point() 

enter image description here

只需添加这两行代码,即可使x和y轴从零开始:

iris %>% 
  ggplot(aes(x=Sepal.Length, y=Sepal.Width)) +
  geom_point() +     
  xlim(0, 8.2) +     # add this line for x axis limits
  ylim(0, 4.5)       # add this line for y axis limits

enter image description here


我猜这不是问题的关键所在。 - Ilona

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接