【问题标题】:incorrect linetype in geom_vline with legend in r ggplot2geom_vline 中不正确的线型与 r ggplot2 中的图例
【发布时间】:2014-09-14 15:11:09
【问题描述】:

我正在尝试将 xvar 中位数显示为虚线并在图例中显示。这是我的代码:

require(ggplot2)
require(scales)

medians_mtcars <- data.frame("wt.median"=median(mtcars$wt))

# legend shows but linetype is wrong (solid)
p <- ggplot(mtcars, aes(wt, mpg))
p <- p + geom_point()
p <- p + geom_vline(aes(xintercept=wt.median, linetype="dotted"),
                    data=medians_mtcars, show_guide=TRUE)
p

我也试过了:

# linetype is correct but legend does not show
p <- ggplot(mtcars, aes(wt, mpg))
p <- p + geom_point()
p <- p + geom_vline(aes(xintercept=wt.median),
                    data=medians_mtcars, show_guide=TRUE, linetype="dotted")
p

本来想发布剧情图片,但尚未超过声誉阈值。

此论坛上还有 2 个其他帖子与此主题相近,但没有提供解决此问题的方法: Add vline to existing plot and have it appear in ggplot2 legend? ; Incorrect linetype in legend, ggplot2 in R

我正在使用 ggplot2 版本 1.0.0

我做错了什么?

提前致谢

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    如果您需要在图例中显示线型并在aes() 中进行更改,您可以只为该线型编写名称(因为您只有一行),然后使用scale_linetype_manual() 更改线型。

    ggplot(mtcars, aes(wt, mpg)) + 
          geom_point() + 
          geom_vline(aes(xintercept=wt.median, linetype="media"),
                        data=medians_mtcars, show_guide=TRUE)+
          scale_linetype_manual(values="dotted")
    

    如果你真的想在aes() 中输入线型并获得正确的图例,那么你应该使用scale_linetype_identity() 和参数guide="legend"

    ggplot(mtcars, aes(wt, mpg)) + 
          geom_point() + 
          geom_vline(aes(xintercept=wt.median, linetype="dotted"),
                        data=medians_mtcars,show_guide=TRUE)+
          scale_linetype_identity(guide="legend")
    

    【讨论】:

    • 非常感谢Didzis。我的任务包含不止一行(例如均值、中位数、标准差等),我在这篇文章中对其进行了简化。我仍然很好奇如何在 aes 映射中指定线型常量,以便图例自动正确显示指定的线型。
    • 做到了。非常感谢。现在我需要去看看 scale_*_identity 是做什么的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    相关资源
    最近更新 更多