r - ggplot 中没有显示刻度线

标签 r ggplot2

我正在绘制一些数据并希望在绘图的 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 的情况下,没有任何刻度线。为什么我的报价没有出现?

最佳答案

在使用 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 已经是离散的,因此不需要使用带有breaksscale_x_discrete

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

enter image description here

如果您希望 x 轴标签与数据框中的不同(即以 1 而不是 0 开头),您可以使用 small调整为:

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

enter image description here

关于r - ggplot 中没有显示刻度线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45566751/

相关文章:

python - 您将如何在 Matplotlib 或 Mayavi 中表示以下 3D 数据?

r - 使用R转换文件编码? (ANSI到UTF-8)

R 'object XX not found' 函数内部抛出错误,但不在脚本中

r - 如何使用ggplot2绘制功率曲线

r - geom_bar() 使条形不同宽度并完全重叠

r - 在scale_shape_manual中分配40个或更多形状

r - 在R中如何解析这个数据类型?

r - 没有读取功能吗?

带有图例限制的反向调色板ggplot2

r - 将 "Overall"组添加到facet_wrap (ggplot2)