【问题标题】:How can I add a background grid using ggplot2?如何使用 ggplot2 添加背景网格?
【发布时间】:2010-11-17 02:36:26
【问题描述】:

我想在绘图中心添加背景网格,然后隐藏标准网格线。网格的角点存储在 pts 数据框中,我尝试使用 geom_tile,但它似乎没有使用指定的点。提前感谢您的帮助。

library(ggplot2)  
pts <- data.frame(
        x=c(170,170,170,177.5,177.5,177.5,185,185,185), 
        y=c(-35,-25,-15,-35,-25,-15,-35,-25,-15))  
ggplot(quakes, aes(long, lat)) + 
    geom_point(shape = 1) + 
    geom_tile(data=pts,aes(x=x,y=y),fill="transparent",colour="black") +
    opts(
        panel.grid.major=theme_blank(),
        panel.grid.minor=theme_blank()
    )

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以手动指定中断:

    ggplot(quakes, aes(long, lat)) + geom_point(shape = 1) +
      scale_x_continuous(breaks = c(170, 177.5, 185)) +
      scale_y_continuous(breaks = c(-35, -25, -15)) +
      opts(panel.grid.minor = theme_blank(), 
           panel.grid.major = theme_line("black", size = 0.1))
    

    那么,这就是你想要的吗?

    pts <- data.frame(x=c(170, 170, 170, 170, 177.5, 185), 
                      y=c(-35, -25, -15, -35, -35, -35),
                      xend=c(185, 185, 185, 170, 177.5, 185),
                      yend=c(-35, -25, -15, -15, -15, -15))
    ggplot(quakes, aes(long, lat)) + geom_point(shape = 1) + 
       geom_segment(data=pts, aes(x, y, xend=xend, yend=yend)) +
       opts(panel.grid.minor = theme_blank(), 
            panel.grid.major = theme_blank())
    

    【讨论】:

    • 我实际上想让网格在后台“浮动”(参见我的示例)。不过还是谢谢。
    • 这正是我想要的——谢谢。我还发现 geom_path 可以工作,但是绘制路径上的所有点非常麻烦: pts
    • 顺便说一句,这不再适用于当前版本的 ggplot2 (1.0.0)。
    【解决方案2】:

    不优雅,但这是我想出的快速而肮脏的东西。不幸的是,我无法在某个点停止线路,它一直到边缘。

    ggplot(quakes, aes(long, lat)) + geom_point(shape = 1)
     + opts(panel.grid.major=theme_blank(),
            panel.grid.minor=theme_blank())
     + geom_vline(aes(xintercept =seq(165,185,by=5)))
     + geom_hline(aes(yintercept=seq(-35,-15,by=5)))
    

    【讨论】:

    • 如果您正在为出版物编辑这样的图形,您可以随时保存为 eps,然后在 Adob​​e Illustrator 中编辑掉多余的行。这就是我会做的。
    猜你喜欢
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多