简体   繁体   English

如何删除geom_col周围的ggplot2背景和裁切边距

[英]How to remove ggplot2 background and crop margins around geom_col

I want to make a "timeline" using a stacked column chart. 我想使用堆积的柱状图制作“时间轴”。 What I want to do is to remove all background so I just have a bar and nothing else. 我想做的是删除所有背景,所以我只有一个酒吧,没有别的。 I am stuck with the white background of the chart. 我被图表的白色背景困住了。

Here is a minimal example: 这是一个最小的示例:

mytheme <-  theme(
        axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        #panel.background = element_blank()
)

Name <- c("One", "Two", "Three", "Four")
value <- c(2, 5, 7, 8)

df <-  data.frame(Name, value)

ggplot(df)+
  aes(x= "Name", y = value,  fill = Name) +
  geom_col(width = .1, show.legend = FALSE) + 
  xlab("") + ylab("") +
  coord_flip() +
  mytheme

giving me a bar but on a big background 给我一个酒吧,但背景广阔 在这里显示 .

(I have commented out the panel.background just to show the extent of the background. I want to "crop" that white background so I have only the bar or just a little space around the bar. Help pls. (我已经注释掉panel.background只是为了显示背景的范围。我想“裁剪”该白色背景,因此我只有条形图或条形图周围只有一点空间。请帮助。

Update 更新资料

After the suggestion by @Gregor, I modified the code ggplot as follows: 在@Gregor的建议之后,我将代码ggplot修改如下:

ggplot(df)+
  aes(x= "Name", y = value,  fill = Name) +
  geom_col(width = .1, show.legend = FALSE) + 
  xlab("") + ylab("") +
  coord_flip(expand = FALSE) +
  mytheme

The result is a very wide bar (tall on page because I have used coord_flip): 结果是一个非常宽的条(页面高,因为我用过coord_flip):

在此处输入图片说明

All I need to do now is to reduce the height (as it is seen in the picture) to make it more like my original bar. 我现在要做的就是减小高度(如图所示),使其更像我的原始条形。 How can I change that? 我该如何改变?

Solution

I finally found a simple solution. 我终于找到了一个简单的解决方案。 As I am using R Markdown , I used: 当我使用R Markdown ,我使用了:

```{r, ..., fig.width=4, fig.height=.3}

in the preamble to the embedded figure. 在嵌入图的序言中。 Not the best solution, but it works. 不是最好的解决方案,但它可以工作。 Thanks to all. 谢谢大家。

This is a very interesting question. 这是一个非常有趣的问题。 Here's one way to approach this: instead of using a vertically stacked bar plot and then flipping it horizontally, we can simply create a "regular" bar plot where the bars are placed adjacent to one another and have equal heights, but each bar has a variable width which is equal to the duration of your desired time intervals. 这是一种解决方法:不使用垂直堆叠的条形图然后将其水平翻转,我们可以简单地创建一个“常规”条形图,其中条形彼此相邻放置并具有相同的高度,但是每个条形都有一个可变宽度,等于所需时间间隔的持续时间。 We can "crop" the background using coord_fixed(expand = FALSE) . 我们可以使用coord_fixed(expand = FALSE) “裁剪”背景。

It is probably best if we directly specify the x-axis positions to ggplot() , so that we can use them to place our labels (more detail about that later) - here's how to position the intervals for your timeline: 最好是直接将ggplot()指定x轴位置,以便我们可以使用它们放置标签(稍后会对此进行详细说明)-这是如何为时间轴定位时间间隔:

Let X i denote the distance (along the x-axis) from the origin to the center of each time interval i . X i表示每个时间间隔i从原点到中心的距离(沿x轴)。 For each interval i , X i is the sum of the lengths of the previous time intervals X 0 : X i - 1 , plus half the length of X i . 对于每个间隔iX i是先前时间间隔X 0 :X i-1的长度的总和,加上X i长度的一半。 We can have R automatically generate these values for us by adding a column that uses a lagged cumulative sum, as you will see below. 我们可以让R通过添加使用滞后累积和的列为我们自动生成这些值,如下所示。

I have left panel.background = element_blank() commented out, so that you can confirm that we do indeed obtain "just the timeline", with no background. 我已经panel.background = element_blank() ,以便您可以确认我们确实获得了“只是时间轴”,没有背景。

Code: 码:

library("tidyverse")

mytheme <-  theme(
  axis.title.x=element_blank(),
  axis.text.x=element_blank(),
  axis.ticks.x=element_blank(),
  axis.title.y=element_blank(),
  axis.text.y=element_blank(),
  axis.ticks.y=element_blank(),
  panel.grid.major = element_blank(),
  panel.grid.minor = element_blank(),
  #panel.background = element_blank()
)

Name <- c("One", "Two", "Three", "Four")
Value <- c(2, 5, 7, 8)

df <-  data.frame(Name, Value) %>%
  mutate(Name = factor(Name, levels = Name),
         xPos = cumsum(lag(Value, default = 0)) + Value/2) # calculate interval position

ggplot(data = df, aes(x = xPos, y = 1, width = Value, fill = Name)) +
  geom_col(position = "identity",
           show.legend = FALSE) +
  geom_text(aes(label = Name),
            position = position_fill(vjust = 0.5)) +
  coord_fixed(expand = FALSE) + # crop background around geom_col()
  mytheme

Output: 输出:

时间线图

Why It Works: 工作原理:

As of ggplot2 version 3.1.0, we are initially caught between a rock and hard place: if we choose to use coord_flip() we can get a horizontal timeline, but we cannot (easily) resize our plotting area to have the dimensions we want. ggplot2版本3.1.0开始,我们最初陷入了困难的境地:如果选择使用coord_flip()我们可以获得水平时间轴,但是我们无法(轻松地)调整绘图区域的大小以具有所需的尺寸。 If we instead use coord_fixed(expand = FALSE) , we have the desired plotting margins, but we cannot easily make a horizontal "stack" of bars, as coord_fixed() is incompatible with coord_flip() . 如果改为使用coord_fixed(expand = FALSE) ,则具有所需的打印边距,但由于coord_fixed()coord_flip()不兼容,因此我们无法轻松地制作水平的条形“堆栈”。

There is an interesting argument called position_dodge2() that you can use with geom_col() to place bars of variable widths adjacent to one another. 有一个有趣的参数,称为position_dodge2() ,您可以将其与geom_col()一起使用,以将宽度可变的钢筋彼此相邻放置。 If you set padding = 0 , you can obtain a plot which appears very similar to what you see above, but the actual "x-coordinates" of each interval will begin at the left edge of each bar, as opposed to the center. 如果将padding = 0设置padding = 0 ,则可以获得与上图非常相似的图,但是每个间隔的实际“ x坐标”将从每个条的左边缘开始,而不是从中心开始。

This makes centering the text labels very difficult, as we would need to adjust their positioning depending on how wide each interval is, but ggplot2 options like position_nudge() only allow us to adjust all of the labels by some constant amount. 这使文本标签居中非常困难,因为我们需要根据每个间隔的宽度来调整它们的位置,但是ggplot2选项(例如position_nudge()仅允许我们将所有标签调整一定的量。 Consequently, we specify the center of each time interval directly. 因此,我们直接指定每个时间间隔的中心。 Hopefully, as ggplot2 continues to improve, we will see options like position_nudge() gain additional functionality to deal with this problem more easily! 希望随着ggplot2不断改进,我们将看到诸如position_nudge()类的选项获得更多功能来更轻松地解决此问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM