更改ggplot2中的图例标签

时间:2019-09-29 14:09:03

标签: r ggplot2 legend legend-properties

我想更改图例中的标签。我知道这听起来很简单,除了实际的图表是交互式的,所以我不知道标签可能采用的值的范围。

一个更简单的图表如下

set.seed(1990)
library(reshape2)
library(viridis)
df <- melt(outer(rnorm(100), rnorm(100)), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_viridis() + coord_equal()

上面应该产生

enter image description here

我想更改图例标签,以便仅将标签放在图例的末端。

例如,在最高点(图表中为8),它将标记为“最高值”,而另一个末端则具有“最低值”。在这两者之间,不需要标签。

在下面的示例中,图例用“相对较低”和“相对较高”来描述图表

enter image description here

1 个答案:

答案 0 :(得分:0)

以下代码用“最高值”和“最低值”重新标记了图例。至于交互位,如果数据是在生成图之前的子集,那么图例将适合数据子集。

library(reshape2)
library(viridis)
library(ggplot2)

set.seed(1990)
df <- melt(outer(rnorm(100), rnorm(100)), varnames = c("X1", "X2"))

low <- min(df$value)
high <- max(df$value)
p1 <- ggplot(df, aes(X1, X2)) + 
  geom_tile(aes(fill = value)) +
  coord_equal() + 
  scale_fill_continuous(type = "viridis", 
                        breaks = c(low, high), 
                        labels = c("Lowest value", "Highest value"))
p1

enter image description here

相关问题