ggplot - 如何覆盖图例值

时间:2014-01-03 09:43:24

标签: r ggplot2 legend

而不是传说中的-2,0,2,4我想要指出这些值,即round(exp(c(-2,0,2,4)),0)之类的东西,如果可能的话,还有一个通用的解决方案(不必使用任何适合每个值的值)情节,在代码中)。 以下是重现下面给出的代码的一些数据。

df <- structure(list(P0 = c(5.55, 3.38, 8.86, 34.23, 16.54, 45.76, 
147.33, 20.04, 36.27, 9.99, 3.01, 2.28, 6, 0.08, 5.81, 4.72, 
3.41, 14.6, 7.55, 1.58, 4.7, 0.39, 1.28, 0.13, 9.1, 0, 107.73, 
14.07, 28.45, 25.27, 1.12, 10.87, 104.55, 51.07, 15.55, 5.34, 
3.13, 4.63, 16.47, 0.55, 6.59, 34.24, 5.4, 0.59, 5.74, 5.53, 
3.3, 22.53, 88.21, 5.01, 1.6, 0.41, 40.19, 25.52, 113.29, 3.32, 
38.36, 86.2, 7.05, 2.63, 10.15, 0.1, 2.01), P = c(8.51, 5.21, 
13.45, 38.04, 29.37, 84.29, 326.2, 37.12, 96.41, 19.68, 3.62, 
3.87, 7.96, 0.67, 6.35, 5.95, 3.41, 38.05, 8.11, 1.58, 8.26, 
0.39, 1.49, 1.15, 12.03, 29.13, 130.14, 42.4, 53.05, 48.02, 1.12, 
16.88, 206.93, 63.14, 16.49, 14.57, 4.17, 4.63, 30.29, 2.64, 
6.59, 35.76, 5.4, 0.68, 5.74, 7.02, 3.3, 37.66, 150.54, 10.63, 
2.93, 11.47, 71.82, 45.25, 175.33, 10.4, 58.88, 86.2, 11.95, 
13.92, 17.18, 0.19, 2.01), T0 = c(2.033, 1.858, 1.525, 3.275, 
2.7, 1.517, 3.042, 2.792, 1.358, 1.858, 2.033, 1.017, 2.025, 
1.017, 1.525, 1.525, 0.675, 2.283, 1.517, 3.042, 1.442, 3.042, 
3.042, 0.85, 1.517, 0.342, 4.058, 1.858, 2.875, 1.858, 1.342, 
1.017, 4.058, 2.708, 1.092, 2.033, 1.525, 1.267, 1.525, 1.525, 
0.675, 2.283, 1.525, 3.042, 1.575, 1.525, 1.525, 2.542, 2.542, 
1.525, 0.592, 0.933, 3.042, 2.5, 3.383, 2.033, 1.533, 3.042, 
1.525, 2.025, 2.2, 1.017, 0.767), year = c(2002L, 2003L, 2003L, 
2001L, 2004L, 2002L, 2002L, 2005L, 2003L, 2003L, 2006L, 2003L, 
2005L, 2006L, 2003L, 2006L, 2003L, 2002L, 2002L, 2003L, 2007L, 
2003L, 2003L, 2003L, 2004L, 2004L, 2007L, 2007L, 2006L, 2007L, 
2006L, 2006L, 2007L, 2006L, 2006L, 2006L, 2006L, 2006L, 2006L, 
2006L, 2006L, 2006L, 2007L, 2005L, 2006L, 2006L, 2006L, 2006L, 
2007L, 2006L, 2006L, 2007L, 2006L, 2006L, 2006L, 2007L, 2007L, 
2013L, 2008L, 2009L, 2009L, 2009L, 2011L)), .Names = c("P0", 
"P", "T0", "year"), class = "data.frame")

到目前为止我的代码是这样的。我已尝试在values中指定scale_colour_continuous,但未被接受。

ggplot(df, aes(year, P0/P)) + 
  geom_point(aes(color=log(P/T0),size=2)) + 
  geom_line(aes(group = year)) +
  scale_x_continuous(breaks = c(2003,2005,2007,2009,2011,2013),labels = c("2003","2005","2007","2009","2011","2013")) +
  scale_y_continuous(labels = percent) +
  scale_size(guide = "none") +
  labs(colour="Color:", x = "Year", y = "Percentage") +
  theme_bw() +
  theme(legend.position = "top",
        legend.key = element_rect(linetype = 0),
        legend.text = element_text(size = rel(1.05)),
        legend.title = element_text(size = rel(1.0), hjust = 0),
        panel.margin = unit(c(1, 1, 2, 0.5), "lines"),
        axis.title.x = element_text(vjust = -.5),
        axis.title.y = element_text(vjust = .2)
  )

1 个答案:

答案 0 :(得分:5)

您可以使用库trans_format()中的scales来使用指数转换标签。 "identity"表示原始标签在function(x)内使用。

 + scale_color_continuous(labels=trans_format("identity", function(x) round(exp(x),0)))