简体   繁体   English

R 如何设置 x 和 y 轴值?

[英]R how can I set x and y axes values?

I am using this R script for plotting these trend:我正在使用这个 R 脚本来绘制这些趋势:

archiveorg <- c(9,10,9,10,11,11,10,12,11,10,14,13,17,17,16,13,17,16,18,15,16,16,17,18)
waybacksafn <- c(2,2,4,2,2,2,2,2,1,2,3,2,4,3,3,4,3,3,4,4,1,2,5,7)
waybacknil <- c(5,0,0,0,0,3,3,1,2,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2)

months <-c(1:24)
df <- data.frame(months,archiveorg,waybacksafn,waybacknil)
plot(df$archiveorg,type='n',xlim=c(1,24),ylim=c(1,19),xlab='tempo', ylab='#siti safe csp')
lines(df$archiveorg, type="l", col="red")
lines(df$waybacksafn, type="l", col="blue")
lines(df$waybacknil, type="l", col="black")

axis(1, at=1:24, lab=df$months)
axis(2, las=1, at=seq(1, 19))
legend(1, 19, legend=c("archiveorg", "waybacksafn","waybacknil"),
col=c("red", "blue","black"), lty=1, cex=0.8)

And the result is the following:结果如下: 在此处输入图像描述

On x axes I have values from 1 to 24 (these represents the months from 2018 to the end of 2019).在 x 轴上,我有从 1 到 24 的值(这些代表从 2018 年到 2019 年底的月份)。 Now i'd like to have only 2018 and 2019 on my x axes (2018 at position 0, and 2019 at position 11).现在我想在我的 x 轴上只有 2018 年和 2019 年(2018 年在 position 0,2019 年在 position 11)。

On y axes I need something similar.. values goes from 1 to 19 but I need only to have 1, 10 and 19 on my axes and no all values.在 y 轴上我需要类似的东西.. 值从 1 到 19 但我只需要在我的轴上有 1、10 和 19 而不是所有值。

How can I change my script for this?我该如何为此更改我的脚本?

You need to draw the plot without axes and specify where you want the breaks and what you want their labels to be:您需要绘制不带轴的 plot 并指定您想要中断的位置以及您希望它们的标签是什么:

plot(df$archiveorg,type = 'n', xlim = c(0, 24), ylim = c(0, 19),
     xlab='tempo', ylab='#siti safe csp', yaxt = 'n', xaxt = 'n')
lines(df$archiveorg, type = "l", col = "red")
lines(df$waybacksafn, type = "l", col = "blue")
lines(df$waybacknil, type = "l", col = "black")

axis(1, at = c(0, 11), lab = c(2018, 2019))
axis(2, las = 1, at = c(1, 10, 19))
legend(1, 19, legend = c("archiveorg", "waybacksafn","waybacknil"),
       col=c("red", "blue","black"), lty = 1, cex = 0.8)

在此处输入图像描述

Needless to say, it would be easier, prettier and allow more scope for customization to do this in ggplot :不用说,在ggplot中执行此操作会更容易、更漂亮并允许更多 scope 进行自定义:

library(tidyverse)
library(lubridate)

df %>% 
  pivot_longer(-1) %>%
  mutate(month = round_date(as.Date("2017-12-01") + 30 * months, "month")) %>%
  ggplot(aes(month, value, colour = name)) + 
  geom_line(size = 1) +
  scale_colour_manual(values = c("red3", "blue4", "cyan3"), name = NULL) +
  scale_x_date(date_breaks = "years", date_labels = "%Y") +
  theme_bw() +
  theme(legend.position = c(0.2, 0.8),
        legend.background = element_rect(color = "black"))

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM