ggplot2:图例与绘图区域重叠 - 是否可以手动调整图例位置?

发布于 2024-11-17 10:52:22 字数 869 浏览 0 评论 0原文

假设我有一个关于不同田地和不同品种的胡萝卜产量的数据集:

carrots<-list(Yield=c(345,226,74,559,288,194),
          Field=c("A","B","C","D","E","F"),
          Breed=rep(c("Long","Short"),each=3))
carrots<-data.frame(carrots)

我想绘制一个条形图,显示每个田地的产量,按品种着色:

ggplot(carrots,aes(y=Yield,x=Field,fill=Breed)) +
   geom_bar() +
   opts(legend.direction = "horizontal",
        legend.position = "top") +
   labs(fill="")

但图例总是与绘图区域稍微重叠:

图例略有重叠
(来源:users.utu.fi

我'我尝试手动将图例位置调整到绘图区域之外,例如使用

opts(legend.position=c(0.5,1.1)

但绘图边距切断了图例,我不确定如何调整它们。对于这个问题有更微妙的解决方案吗?

Lets say I have a dataset about carrot yield from different fields and different breeds:

carrots<-list(Yield=c(345,226,74,559,288,194),
          Field=c("A","B","C","D","E","F"),
          Breed=rep(c("Long","Short"),each=3))
carrots<-data.frame(carrots)

I want to plot a bar plot showing the yield for each field, coloured by breed:

ggplot(carrots,aes(y=Yield,x=Field,fill=Breed)) +
   geom_bar() +
   opts(legend.direction = "horizontal",
        legend.position = "top") +
   labs(fill="")

But the legend is always slightly overlapping the plot area:

plot with slight legend overlap
(source: users.utu.fi)

I've tried manually adjusting the legend position to be outside the plot area, such as with

opts(legend.position=c(0.5,1.1)

but then the plot margins cut off the legend and I'm not sure how I can adjust them. Is there a more subtle solution to this problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

毅然前行 2024-11-24 10:52:22

在我的环境中,图例根本不与绘图区域重叠,但无论如何重叠的是图例的背景,因此您可以通过以下方式将其删除:

ggplot(carrots,aes(y=Yield,x=Field,fill=Breed)) +
 geom_bar() +
 opts(legend.direction = "horizontal",
    legend.position = "top",
        legend.background = theme_blank()) + # this does hack
 labs(fill="")

In my environment, the legend does not overlap the plot area at all, but anyway what is overlapping is the background of the legend, so you can remove it by:

ggplot(carrots,aes(y=Yield,x=Field,fill=Breed)) +
 geom_bar() +
 opts(legend.direction = "horizontal",
    legend.position = "top",
        legend.background = theme_blank()) + # this does hack
 labs(fill="")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文