【问题标题】:Label affects legend symbols in ggplot标签影响ggplot中的图例符号
【发布时间】:2017-04-19 16:09:01
【问题描述】:

我有一个包含两个不同变量的数据集 - 城市和城镇

当我绘制它们并使用stat_smooth 添加两条回归线时,图例符号显示不正确(它们显示为两个'a'):

ggplot(metrics, aes(x=popDensity, y= TPB, color = factor(type))) + geom_point() +theme_minimal() + stat_smooth(method = "lm", se = FALSE) +
  geom_label_repel(aes(label= rownames(metrics)), size=3) +
  theme(axis.title = element_text(family = "Trebuchet MS", color="#666666", face="bold", size=12)) +
  labs(x = expression(paste( "density ", km^{2})), y = expression(paste("rating[![enter image description here][1]][1]")))+
  theme(legend.position="top", legend.direction="horizontal") 

这是结果:

但是,当我删除 geom_label_repel 函数时,我得到了我需要的图例符号 - 但当然标签不会出现。

ggplot(metrics, aes(x=popDensity, y= TPB, color = factor(type))) + geom_point() +theme_minimal() + stat_smooth(method = "lm", se = FALSE) +
  #geom_label_repel(aes(label= rownames(metrics)), size=3) +
  theme(axis.title = element_text(family = "Trebuchet MS", color="#666666", face="bold", size=12)) +
  labs(x = expression(paste( "density ", km^{2})), y = expression(paste("rating")))+
  theme(legend.position="top", legend.direction="horizontal")

为什么会发生这种情况?是否有针对此问题的已知解决方法?另外,有没有办法手动更改图例标题的标题?我试过使用+ theme(legend.title = "title") 但得到错误:

Error in (function (el, elname)  : 
  Element legend.title must be a element_text object.

样本数据:

> dput(metrics)
structure(list(popDensity = c(4308, 27812, 4447, 5334, 4662, 
2890, 24623, 5847, 1689, 481, 4100), TPB = c(1, 0.5, 1, 1.3, 
0.8, 4, 0.2, 0.7, 5, 4, 2), type = c("City", "City", "City", 
"City", "City", "City", "Town", "Town", "Town", "Town", "Town"
)), .Names = c("popDensity", "TPB", "type"), row.names = c("City1", 
"City2", "City3", "City4", "City5", "City6", "Town1", "Town2", 
"Town3", "Town4", "Town5"), class = "data.frame")

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    在您的 geom_label_repel 通话中添加 show.legend = FALSEa's 似乎是标签的标准图例,它覆盖了使用相同颜色的 geom_point

    【讨论】:

    • 谢谢 - 如何将图例的标题从 factor(type) 更改为其他名称?
    • 然后我得到Error in f(...) : argument "values" is missing, with no default
    • 对不起 - 这应该工作+ scale_colour_discrete(name="something else")。我总是对色阶有问题!
    猜你喜欢
    • 1970-01-01
    • 2015-02-25
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多