r - 在主标题上方放置图例

标签 r ggplot2 legend

将图例置于 ggplot2 中的主标题上方使用时 theme(legend.position = "top")似乎是以前版本的 ggplot 中的默认(和不需要的)结果:ggplot legend at top but below title?

当前版本ggplot2 , 设置 theme(legend.position = "top") 时,图例将自身置于情节和主标题之间.一个小例子:

d <- data.frame(x = 1:2, y = 1:2, z = c("a", "b")) 
ggplot(d, aes(x = x, y = y, fill = z)) + 
  geom_col() +
  ggtitle("My title") +
  theme(legend.position = "top") 

enter image description here

如何将图例放在主标题上方?

最佳答案

library(ggplot2)

ggplot(mtcars, aes(wt, mpg, color=cyl)) +
  geom_point() +
  labs(title = "Hey") +
  theme(plot.margin = margin(t=4,1,1,1, "lines")) +
  theme(legend.direction = "horizontal") +
  theme(legend.position = c(0.5, 1.2))

enter image description here

还有其他方法,但这是想到的最简单的方法。

关于r - 在主标题上方放置图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52784538/

相关文章:

r - 将特定图例添加到 R 绘图中

python - Matplotlib:为 numpy 数组的每一列添加图例

r - R 绘图图例行为中的换行

R 检查重复项非常慢,即使使用 mclapply

r - 更改 ggplot 中的调色板

r - 循环在ggplot中绘制几条拟合曲线?

r - 突出显示图中的最高残差 : R

r - 获取元素随机从另一个表B取数据表

r - 解析时间并转换为分钟

r - 根据 R 中的模式集合提取数字