在R的geom_line中添加标签

问题描述 投票:2回答:1

我有两个非常相似的图,它们有两个y轴-条形图和线形图:

enter image description here

代码:

sec_plot <- ggplot(data, aes_string (x = year, group = 1)) +
    geom_col(aes_string(y = frequency), fill = "orange", alpha = 0.5) +
    geom_line(aes(y = severity))  

但是,没有标签。我想为条形图以及线图获得标签,例如:

enter image description here

如果只有一个人组,如何将标签添加到绘图中?有没有办法手动指定?直到我才知道只有在aes

中指定标签的地方可以添加标签
r ggplot2 axis-labels
1个回答
0
投票

这里是一个可能的解决方案。我使用的方法是移动颜色并填充到aes内部,然后使用scale _ * _ identity创建和设置图例格式。另外,由于ggplot不能很好地处理辅助轴,因此我需要为严重度轴添加比例因子。

data<-data.frame(year= 2000:2005, frequency=1*(3:8), severity=as.integer(runif(6, 4000, 8000)))

library(ggplot2)
library(scales)

sec_plot <- ggplot(data, aes(x = year)) +
  geom_col(aes(y = frequency, fill = "orange"), alpha = 0.6) +
  geom_line(aes(y = severity/1000, color = "black", group=1)) +
  scale_fill_identity(guide = "legend", label="Claim frequency (Number of paid claims per 100 Insured exposure)", name=NULL) +
  scale_color_identity(guide = "legend", label="Claim Severity (Average insurance payment per claim)", name=NULL) +
  theme(legend.position = "bottom") +
  scale_y_continuous(sec.axis =sec_axis( ~ . *1, labels = label_dollar(scale=1000), name="Severity") ) +  #formats the 2nd axis
  guides(fill = guide_legend(order = 1),  color = guide_legend(order = 2))                                #control which scale plots first

sec_plot

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.