消除垂直线ggplot [英] Eliminate vertical lines ggplot

查看:58
本文介绍了消除垂直线ggplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题曾被问过,但答案并不总是很清楚或很复杂.我希望ggplot2的更新版本能够带来更简单的解决方案.

This question has been asked before but the answers aren't always clear or are complicated. I'm hoping that newer versions of ggplot2 have lead to easier solutions.

如何消除ggplot的垂直线而不消除轴刻度线或标签?这对于条形图确实非常好,因为它可以消除图形上不必要的干扰.

How can you eliminate just the vertical lines of a ggplot without eliminating the axis tick marks or labels? This would really be nice for bar graphs as it would eliminate some unnecessary distraction from the graphic.

以下是一些有助于讨论的示例代码:

Here is some sample code to aid the discussion:

library(ggplot2)
set.seed(10)
CO3 <- data.frame(id=1:nrow(CO2), CO2[, 2:3], 
           outcome=factor(sample(c('none', 'some', 'lots', 'tons'), 
           nrow(CO2), rep=T), levels=c('none', 'some', 'lots', 'tons')))
CO3
x <- ggplot(CO3, aes(x=outcome)) + geom_bar(aes(x=outcome))+ 
     facet_grid(Treatment~Type, margins='Treatment', scales='free') 
x +  theme_bw() + opts(axis.text.x=theme_text(angle= 45, vjust=1, hjust= 1))

推荐答案

尝试一下,重新定义guide_grid.

Try this, redifining guide_grid.

此解决方案来自 R的食谱

# Save the original definition of the guide_grid
guide_grid_orig <- ggplot2:::guide_grid

# Create the replacement function
guide_grid_no_vline <- function(theme, x.minor, x.major, y.minor, y.major) {  
  x.minor <- setdiff(x.minor, x.major)
  y.minor <- setdiff(y.minor, y.major)

  ggname("grill", grobTree(
    theme_render(theme, "panel.background"),
    if(length(y.minor) > 0) theme_render(
      theme, "panel.grid.minor", name = "y",
      x = rep(0:1, length(y.minor)), y = rep(y.minor, each=2), 
      id.lengths = rep(2, length(y.minor))
      ),
    if(length(y.major) > 0) theme_render(
      theme, "panel.grid.major", name = "y",
      x = rep(0:1, length(y.major)), y = rep(y.major, each=2), 
      id.lengths = rep(2, length(y.major))
      )
    ))
}
# Set the environment to be the same as original
environment(guide_grid_no_vline) <- environment(ggplot2:::guide_grid)

# Assign the function inside ggplot2
assignInNamespace("guide_grid", guide_grid_no_vline, ns="ggplot2")

# Draw the plot with the redefined guide_grid
ggplot(CO3, aes(x=outcome)) + 
  geom_bar(aes(x=outcome))+ 
  facet_grid(Treatment~Type, margins='Treatment', scales='free')  +
  theme_bw() + 
  opts(axis.text.x=theme_text(angle= 45, vjust=1, hjust= 1))

# Restore the original guide_grid function so that it will draw all gridlines again
assignInNamespace("guide_grid", guide_grid_orig, ns="ggplot2")

这篇关于消除垂直线ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆