ggplot2 - 将数字轴标题更改为字符串向量

bmc*_*bmc 5 string label axis r ggplot2

到目前为止,我的 ggplot 编译有以下内容:

在此处输入图片说明

这次我得到了恰到好处的轴......使用以下代码片段:

p<- p + ylim(c(0,100))
p<- p + geom_hline(aes(yintercept=0))

p<- p + scale_x_continuous(breaks = c(seq(1940,1985,by=5)))
p
Run Code Online (Sandbox Code Playgroud)

所以我有一个从 1940 年到 1985 年以 5 为步长x 轴和一个从 0-100 以 20 为步长y 轴......

第一个问题

如何使 100 出现在 y 轴上?

第二个问题

如何将我的 x 标签更改为以下字符串向量?

abbrev_x <- c("1940","'45","'50","'55","'60","'65","'70","'75","'80","'85")
abbrev_y <- c("0","20","40","60","80","100%")
Run Code Online (Sandbox Code Playgroud)

因此,我发现的最佳解决方案是围绕scale_x_continuous,以下代码片段示例建议使用已经存在的字符串轴标签:

p + scale_x_discrete(limit = c("I1", "SI2", "SI1"),
                 labels = c("Ione","SItwo","SIone"))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

这当然是一个问题,因为我想写的是以下内容:

abbrev_x <- c("1940","'45","'50","'55","'60","'65","'70","'75","'80","'85")
abbrev_y <- c("0","20","40","60","80","100%")
p<- p + scale_x_continuous(breaks = abbrev_x)
p<- p + scale_y_continuous(breaks = abbrev_y)
p
Run Code Online (Sandbox Code Playgroud)

但这在我现在的世界中似乎是一个虚构的现实。为了证明这种虚构,这里是以下错误代码,其中包括我调整的:

Error in x - from[1] : non-numeric argument to binary operator
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

Psi*_*dom 7

您需要两个参数才能正确标记连续轴:

  • 休息:指定放置标签的位置
  • 标签:指定在轴上放置哪些标签

scale_x/y_continuous函数中:

示例数据框

df <- data.frame(YearOfBirth = seq(1940,1985,by=5), AverageProbability = runif(10) * 100)

abbrev_x <- c("1940","'45","'50","'55","'60","'65","'70","'75","'80","'85")
abbrev_y <- c("0","20","40","60","80","100%")

ggplot(df, aes(x = YearOfBirth, y = AverageProbability)) + 
    geom_line(col = "burlywood3") + 
    scale_x_continuous(breaks = seq(1940,1985,by=5), labels = abbrev_x) + 
    scale_y_continuous(breaks = (0:5)*20, labels = abbrev_y, limits = c(0, 110))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明