ggplot中未出现刻度标记

3

我正在绘制一些数据,并希望在我的图表的x轴上标记刻度。我的数据长这样:

  publication   labels   percentage
1 foo           0       .4572
2 foo           1       .0341
3 foo           2       .09478
4 foo           3       .0135
5 bar           0       .7442
6 bar           1       .2847

每个名称都有从0到9的标签。

我的代码如下:

ggplot(aes(y = percentage, x = labels, color = publication), data = labelsdf)+
  geom_point(size = 3)+
  scale_x_discrete(breaks = c(0,1,2,3,4,5,6,7,8,9),
                   labels = c('1','2','3','4','5','6','7','8','9','10'))

但是我的图形看起来像这样:

enter image description here

如果没有指定breakslabels,也没有任何刻度标记。为什么我的刻度不显示?

2
没有展示数据的情况下,无法回答这个问题。可能的情况是你所有的实际数据都落在两个指定的刻度之间。 - Remko Duursma
@snapcrack 你使用的是哪个版本的 ggplot2 - Prradep
@Prradep 2.2.1.9000。对于Remko,我添加了一些数据;我没有考虑添加它,因为它具有直接离散值,但希望这有所帮助。 - snapcrack
“publication”列或向量不存在。 - Prradep
我不小心把它重命名为“name”,然后又改回来了。 - snapcrack
你还应该将 label 更改为 labels - Prradep
1个回答

3

在使用 scale_x_discrete 明确提到 labels 为离散值之后,您需要使用 factor() 将它们作为离散值,否则这些值仍然是数值型的。

ggplot(aes(y = percentage, x = factor(labels), color = publication), data = df)+
  geom_point(size = 3)+
  scale_x_discrete(breaks = c(0,1,2,3,4,5,6,7,8,9),
                   labels = c('1','2','3','4','5','6','7','8','9','10'))

enter image description here

使用后,您可能希望根据需要更改轴标签。


由于labels已经是离散的,因此不需要使用scale_x_discretebreaks

ggplot(aes(y = percentage, x = labels, color = publication), data = df)+
  geom_point(size = 3)

enter image description here

如果您想要以与数据框不同的方式显示x轴标签(即从1开始而不是从0开始),可以使用以下小技巧:

ggplot(aes(y = percentage, x = labels+1, color = publication), data = df)+
  geom_point(size = 3)

enter image description here


2
Factor函数可行。我还应该补充一点,即我发现使用“scale_x_continuous”也可以在不对变量进行因式分解的情况下工作。不应用“scale_x_discrete”的问题是最终会得到无用的刻度,如2.5、5、7.5等。 - snapcrack

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