ggplot扩展图例颜色条

时间:2019-01-03 20:01:21

标签: r ggplot2 legend heatmap

我正在尝试在ggplot上制作热图。我有一个类似于下面的数据框

# This is the format I want to show on the graphs
# Title Graph1 = "Total pH"  (no super or subscripts)
# Title Graph2 = "Total NO3-"  where "3" subscript and "-" superscript
# Title Graph3 = "Total H2PO3-" where "2" subscript, "3" subscript, and "-" superscript
# Title Graph4 = "Total K+" where "+" is superscript

n <- c("pH", "NO3-", "H2PO3-", "K+")

for (j in n) {
    dev.new(width=10, height = 10)
    plot (x=2,y=3, main=j)
}

我的代码是:

wday    hour    quant
Mon 0   1.2346944
Tue 0   0.8418860
Wed 0   0.8904375
Thu 0   0.8906767
Fri 0   1.0761553
Sat 0   2.1095617
Sun 0   2.1421696
Mon 1   2.9178615
Tue 1   0.7481875
Wed 1   0.6200556
Thu 1   0.5530000
Fri 1   0.3852611
Sat 1   0.4791192
Sun 1   1.0958043
Mon 2   2.8627222
Tue 2   0.7989769
Wed 2   0.4209105
Thu 2   0.6512810
Fri 2   0.5047176
Sat 2   0.6544059
Sun 2   0.8167846

它呈现出这样的图形:

enter image description here

您会看到图例的颜色条确实收缩了,如何水平扩展图例使其变宽?

1 个答案:

答案 0 :(得分:1)

legend.key.width是您想要的。例如,

ggplot(df , aes(x = hour, y = wday)) +
  geom_raster(aes(fill = quant), interpolate = TRUE) +
  scale_fill_distiller(palette = "Spectral") + 
  theme(legend.position = "bottom", legend.key.width = unit(2.5, "cm"))

enter image description here