【问题标题】:How can I force ggplot to show more levels on the legend?如何强制 ggplot 在图例上显示更多级别?
【发布时间】:2017-11-18 06:47:08
【问题描述】:

我正在尝试创建一个复杂的 ggplot 图,但有些事情没有按预期工作。

我已经提取了有问题的部分,点的创建及其相关的图例。

library(data.table)
library(ggplot2)
lev <- c("A", "B", "C", "D") # define levels.
bb <- c(40, 30,20,10,5)/100 # define breaks.
ll <- c("40%","30%","20%","10%","5%") # labels.
# Create data
nodos <- data.table(event = c("A", "B", "D", "C", "D"), ord = c(1, 2, 3, 3, 4),
NP = c(0.375, 0.25, 0.125, 0.125, 0.125))


ggplot() + geom_point(data=nodos,aes(x=ord, 
 y=event, size=NP), color="black", shape=16) +
 ylim(lev)  + scale_size_continuous(name="Prop.",
 breaks=bb, labels=ll, range=c(0,6))+ 
 scale_x_continuous(limits=c(0.5, 4.5),
 breaks=seq(1,4,1))

如您所见,无论我使用什么中断和标签,我都无法强制 ggplot 绘制包含 0% 或 10% 的图例。 scale_size_continuous 只创建两个元素。
而且小点的缩放比例很差。

我也尝试过使用 scale_scale_area,但它也不起作用。

我正在使用 R 3.4.2 和 ggplot2 2.2.1(也尝试了最新的 github 版本)。

我怎样才能得到它?

【问题讨论】:

  • 没有安装包。您的数据集有一个名为 evetype 的变量,然后您调用变量 event....
  • 抱歉,打错字了。
  • @AntoniosK 用你的技巧创建了图例,但点的大小与原始值没有任何关系(不是线性的)。你可以把一个很大的来检查一下。
  • @AntoniosK 转换数据似乎没有帮助。我尝试将所有 NP 乘以 100,但我仍然在图例中得到 2 个元素。
  • 您是否尝试在scale_size_continuous 中定义limits?您的大部分breaks 目前都在默认limits 之外,因此添加limits = c(.05, .4) 之类的内容将允许它们显示。看看这看起来是否更像您预期的结果。

标签: r ggplot2


【解决方案1】:

如果您将limits 设置为包含breaks,您将能够更改图例。目前大部分breaks 都超出了比例的默认限制。

ggplot() + 
    geom_point(data = nodos,
               aes(x = ord, y = event, size = NP), color="black", shape = 16) +
    scale_size_continuous(name = "Prop.",
                          breaks = bb,
                          limits = c(.05, .4),
                          labels = ll,
                          range = c(0, 6) )

【讨论】:

    猜你喜欢
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 2019-07-14
    相关资源
    最近更新 更多