【问题标题】:ggplot with a secondary y axis具有辅助 y 轴的 ggplot
【发布时间】:2021-03-14 05:24:19
【问题描述】:

我有以下整齐格式的数据集。我想创建一个ggplotReserves (NAD) 变量作为geom_bar(左轴上的刻度)和Reserves (USD) 变量geom_line(右轴上的刻度)。在同一张图表上绘制两者最简单的方法是什么?

structure(list(Date = structure(c(18170, 18201, 18231, 18262, 
18293, 18322, 18353, 18383, 18414, 18444, 18475, 18506, 18536, 
18170, 18201, 18231, 18262, 18293, 18322, 18353, 18383, 18414, 
18444, 18475, 18506, 18536), class = "Date"), Key = c("Reserves (NAD)", 
"Reserves (NAD)", "Reserves (NAD)", "Reserves (NAD)", "Reserves (NAD)", 
"Reserves (NAD)", "Reserves (NAD)", "Reserves (NAD)", "Reserves (NAD)", 
"Reserves (NAD)", "Reserves (NAD)", "Reserves (NAD)", "Reserves (NAD)", 
"Reserves (USD)", "Reserves (USD)", "Reserves (USD)", "Reserves (USD)", 
"Reserves (USD)", "Reserves (USD)", "Reserves (USD)", "Reserves (USD)", 
"Reserves (USD)", "Reserves (USD)", "Reserves (USD)", "Reserves (USD)", 
"Reserves (USD)"), Value = c(32469.69683154, 29752.37718804, 
28940.88482301, 30961.07351507, 32168.72169411, 32973.94333811, 
35659.4389906, 32944.455576, 31758.97192528, 35399.5709836, 33387.0647566, 
32665.79275848, 34353.83925875, 2150.23984845138, 2030.39391190091, 
2067.39803146078, 2062.61398712044, 2052.95138288458, 1846.74175243683, 
1924.51004045528, 1877.39090357876, 1833.55302380232, 2081.25035179437, 
1971.35496109494, 1952.07290341642, 2114.88932754343)), row.names = c(NA, 
-26L), class = c("tbl_df", "tbl", "data.frame"))

【问题讨论】:

标签: r ggplot2


【解决方案1】:

这就是您如何将条形图和折线图绘制在一起,同时使它们具有可比性。

基本上,这个想法是根据绘制条形的向量的均值和 sd 来更改绘制线条的向量的均值和 sd。必须在第二个 y 轴上应用相反的变换,以使其与您绘制的线相当。

library(ggplot2)
library(tidyr)

# user defined function:
# apply mean and sd of the second vector to the first one
renormalize <- function(from, to){

 from <- scale(from) 
 to <- scale(to) 
 from * attr(to, 'scaled:scale') + attr(to, 'scaled:center')
 
}


# reshape 
df <- df %>% 
 pivot_wider(names_from = Key, values_from = Value)

ggplot(df, aes(x = Date)) +
 geom_col(aes(y = `Reserves (NAD)`), fill = "steelblue") +
 geom_line(aes(y = renormalize(`Reserves (USD)`, `Reserves (NAD)`)), colour = "coral", size = 2) +
 scale_y_continuous(sec.axis = sec_axis(~renormalize(., df$`Reserves (USD)`), name = "Reserves (USD)")) +
 theme_light()

【讨论】:

    【解决方案2】:
    #assign variable table to your tibble
    
    library(ggplot2)
    
    View(table)
    
    typeof(table)
    
    plot = ggplot(data = table, aes(x= Date,y= Value, color=Key)) + geom_bar(stat='identity')
    plot + geom_line()
    
    

    enter image description here

    【讨论】:

      猜你喜欢
      • 2019-11-25
      • 2020-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多