【问题标题】:plot this in ggplot. Controlling y axis line within a range在ggplot中绘制这个。控制y轴线在一个范围内
【发布时间】:2017-03-01 08:51:53
【问题描述】:

这是使用base,我可以控制x和y轴范围,应该在哪里画线。

plot(mtcars$mpg, mtcars$hp, ylim = c(0, 400), xlim = c(0, 50), axes = F, xlab  = 'mpg', ylab = 'hp', pch = 16)
axis(side = 2, at = seq(100, 400, 100))
axis(side = 1, at = seq(10, 30, 10))

ggplot(data = mtcars, aes(x = mpg, y = hp))+geom_point()+
theme(panel.background = element_blank())+
scale_x_continuous(breaks = seq(10, 30, 10), limits = c(0, 50))+
scale_y_continuous(breaks = seq(100, 400, 100), limits = c(0, 400))

如何添加与基本图完全相同的轴线?我试过scale_y_continuousscale_x_continuous,但它总是画到情节结束。

【问题讨论】:

    标签: r plot ggplot2 axis


    【解决方案1】:

    您可以使用ggthemes 包到达那里:

    library(ggthemes)
    ggplot(data = mtcars, aes(x = mpg, y = hp))+geom_point()+
        geom_rangeframe(data = data.frame(mpg = c(10, 30), hp = c(100, 400))) +
        theme_tufte() +
        scale_x_continuous(breaks = seq(10, 30, 10), limits = c(0, 50))+
        scale_y_continuous(breaks = seq(100, 400, 100), limits = c(0, 400))
    

    如果您愿意,也可以手动绘制它们:

    ggplot(data = mtcars, aes(x = mpg, y = hp))+geom_point()+
        geom_segment(aes_all(c('x', 'y', 'xend', 'yend')),
                     data = data.frame(x = c(0, 10), xend = c(0, 30), y = c(100, 0), yend = c(400, 0))) +
        theme(panel.background = element_blank()) +
        scale_x_continuous(breaks = seq(10, 30, 10), limits = c(0, 50), expand = c(0, 0))+
        scale_y_continuous(breaks = seq(100, 400, 100), limits = c(0, 400), expand = c(0, 0))
    

    【讨论】:

    • 谢谢,我以前试过(使用theme_hc())。但我想在不使用 ggthemes 的情况下做到这一点。有可能吗?
    • 我猜你可以在旋转刻度扩展时手动绘制线段。
    • 是的,这就是我的想法。我会试试的。令人惊讶的是,如此成熟的 ggplot 却没有选择。
    • @PoisonAlien,见编辑。值得一提的是,ggplot 是可扩展的。我认为明智的选择是不要在主包本身中包含很多东西,而是让包更纤细,并为用户提供附加组件。
    • 有道理。毕竟有很多附加组件建立在它之上。感谢您的编辑。它有效。
    猜你喜欢
    • 2014-07-10
    • 2015-10-17
    • 2021-05-17
    • 1970-01-01
    • 2020-04-05
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多