ggplot 中带有辅助轴的图形,主要数据不为负

问题描述

我有遵循这种格式的数据,其中 n 是样本数,Change 是从第 n 年到第 n+1 年的百分比变化:

   group  year     n Change
   <chr> <dbl> <dbl>  <dbl>
 1 a      2015    47  NA   
 2 a      2016    80  70.2 
 3 a      2017    52 -35   
 4 a      2018    90  73.1 
 5 a      2019    89  -1.11
 6 a      2020    36 -59.6 
 7 b      2015    20  NA   
 8 b      2016    27  35   
 9 b      2017    97 259.  
10 b      2018    67 -30.9 
11 b      2019    96  43.3 
12 b      2020     4 -95.8 
13 c      2015    57  NA   
14 c      2016    76  33.3 
15 c      2017    19 -75   
16 c      2018    28  47.4 
17 c      2019    66 136.  
18 c      2020    49 -25.8 
19 d      2015    87  NA   
20 d      2016    97  11.5 
21 d      2017    71 -26.8 
22 d      2018    92  29.6 
23 d      2019    89  -3.26
24 d      2020    35 -60.7 
25 e      2015    56  NA   
26 e      2016    83  48.2 
27 e      2017    65 -21.7 
28 e      2018    70   7.69
29 e      2019    79  12.9 
30 e      2020    94  19.0 
31 f      2015    38  NA   
32 f      2016    57  50   
33 f      2017    68  19.3 
34 f      2018    42 -38.2 
35 f      2019    75  78.6 
36 f      2020     9 -88 

我想将 n 个值打印为条形图,趋势线覆盖在条形图上。如果可能,我希望在条形上方显示趋势线,但可以将它们打印在条形顶部。

我在 ggplot 中使用 sec.axis 时遇到问题 - 它不断使我的主轴数据变为负数,而我不希望它这样做。我正在尝试使用基本缩放(例如乘以 0.1)以及此转换将数据转换为不同的比例:

trans_foo <- function(x,mn,mx) {
  (mx - mn)*((x - min(x))/(max(x) - min(x))) + mn
}

但是,图表在 x 轴上显示了最小可能值,我想避免这种情况:

testdata %>% ggplot(aes(x = year,group = group)) + geom_bar(aes(y=n,color = group,fill = group),stat = "identity")   + geom_line(aes(y = Change))+   scale_y_continuous(

    # Features of the first axis
    name = "n",# Add a second axis and specify its features
    sec.axis = sec_axis(trans = ~trans_foo(
      .,100
    ),name="Change")
  )+ geom_line(aes(y = Change,group = group))+ facet_wrap(~group,scales = "free_y")+ theme_minimal() 

我得到的输出是这样的:

enter image description here

我想将趋势线向上移动,并且左侧 y 轴上没有任何负值。谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)