如何使x轴文本具有垂直方向(不以角度= 90/270旋转)

时间:2018-10-22 14:06:25

标签: r ggplot2

我希望我的X轴文本如下所示:

J
一个
n

不能在字母旋转的情况下旋转。

我想将其保留为日期轴。我知道我可以使用例如"J\na\na\n"的值使其离散。也许我可以将类似值的向量映射到axis.text.x值上?似乎应该有一种更简单的方法。

下面将演示该问题。我已经将其旋转了90度,但如上所述,这不是我想要的。

library(tidyverse)
library(scales)

y<- c(52014,51598,61920,58135,71242,76254,63882,64768,53526,55290,45490,35602)
months<-seq(as.Date("2018-01-01"),as.Date("2018-12-01"),"month")
dat<-as.tibble(cbind(y,months)) %>% 
  mutate(month=as.Date(months,origin="1970-01-01"))

ggplot(dat) +
  geom_line(aes(x=month,y=y)) +
  scale_x_date(breaks=date_breaks("month"),labels=date_format("%b")) +
  theme(axis.text.x=element_text(angle=90))

1 个答案:

答案 0 :(得分:2)

示例数据:

date <- seq(from = as.Date("2000-01-01"), to = as.Date("2000-12-01"), by = "month")
df <- data.frame(Month = date, Value = rnorm(12))

首先,生成所需的一组自定义日期。在这里,我使用strsplit()lapply来满足您的请求。(month.namemonth.abb是R中的本机字符向量)

mon.split <- strsplit(month.name, "")
mon <- unlist(lapply(mon.split, paste0, "\n", collapse = ""))
mon
 [1] "J\na\nn\nu\na\nr\ny\n"       "F\ne\nb\nr\nu\na\nr\ny\n"   
 [3] "M\na\nr\nc\nh\n"             "A\np\nr\ni\nl\n"            
 [5] "M\na\ny\n"                   "J\nu\nn\ne\n"               
 [7] "J\nu\nl\ny\n"                "A\nu\ng\nu\ns\nt\n"         
 [9] "S\ne\np\nt\ne\nm\nb\ne\nr\n" "O\nc\nt\no\nb\ne\nr\n"      
[11] "N\no\nv\ne\nm\nb\ne\nr\n"    "D\ne\nc\ne\nm\nb\ne\nr\n"

我认为您的日期变量是'Date'类,因此我使用scale_x_date。如果是数字或字符,请使用scale_x_continuousscale_x_discrete

ggplot(df, aes(x = Month, y = Value)) +
  geom_line() +
  scale_x_date(breaks = date, labels = mon)

enter image description here