我正在绘制一些数据并希望在绘图的 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'))
但我的图表看起来像:
在没有指定 breaks
或 labels
的情况下,没有任何刻度线。为什么我的报价没有出现?
最佳答案
在使用 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'))
使用后,您可能希望根据需要更改轴标签。
由于labels
已经是离散的,因此不需要使用带有breaks
的scale_x_discrete
。
ggplot(aes(y = percentage, x = labels, color = publication), data = df)+
geom_point(size = 3)
如果您希望 x 轴标签与数据框中的不同(即以 1
而不是 0
开头),您可以使用 small调整为:
ggplot(aes(y = percentage, x = labels+1, color = publication), data = df)+
geom_point(size = 3)
关于r - ggplot 中没有显示刻度线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45566751/