【R>>ggplot2】sec.axis第2坐标轴

ggplot2画图展示时,可用sec.axis直接添加标签。

核心函数:

scale_x_date(expand=c(0,0))+ #时间从原点(0,0)开始
  scale_y_continuous(
    limits = c(0,3600),
    expand = c(0,0),
    sec.axis = dup_axis(
      breaks = stock_last_df$last,
      labels = stock_last_df$company,
      name = NULL
    )
  )+
  guides(color="none")

示例数据是科技公司随着时间变化的数据(时间序列数据)

rm(list = ls())
library(tidyverse)
theme_set(theme_bw(16))
stock_df <- data.table::fread("D:/jianshu/R-sec.axis/link2data.txt",data.table = F)
head(stock_df,3)
##   company       date   price
## 1    AMZN 2020-01-02 1898.01
## 2    AMZN 2020-01-03 1874.97
## 3    AMZN 2020-01-06 1902.88
stock_df %>% 
  ggplot(aes(date,price,color=company))+
  geom_line()
image.png

在按照company分组时,在图的右侧会自动匹配图例,但是数目比较多时,效果就不是那么友好了,这时候就需要sec.axis发挥作用了。

stock_last_df <- stock_df %>% 
  group_by(company) %>% 
  summarise(last=dplyr::last(price))
head(stock_last_df)
## # A tibble: 5 x 2
##   company  last
##      
## 1 AMZN    3333 
## 2 FB       303.
## 3 GOOGL   2242.
## 4 NFLX     540.
## 5 TSLA     732.

下面用sec.axis添加labels

stock_df %>% 
  ggplot(aes(date,price,color=company))+
  geom_line()+
  scale_x_date(expand=c(0,0))+ #时间从原点(0,0)开始
  scale_y_continuous(
    limits = c(0,3600),
    expand = c(0,0),
    sec.axis = dup_axis(
      breaks = stock_last_df$last,
      labels = stock_last_df$company,
      name = NULL
    )
  )+
  guides(color="none")
image.png

备注:本文翻译整理自datavizpyr,仅供学习研究使用,如有侵权,请联系删除。

参考链接:

How to Add Labels Directly in ggplot2? Hint: Use Secondary Axis Trick

你可能感兴趣的:(【R>>ggplot2】sec.axis第2坐标轴)