【问题标题】:Moving position of stacked bar in ggplot2 R closer to the y-axisggplot2 R中堆叠条的移动位置更靠近y轴
【发布时间】:2020-06-07 14:43:35
【问题描述】:

我正在寻求有关我为生成堆叠条形图而编写的一些 R 代码的帮助。这是使用 ggplot2 包。这是我的代码:

Plot1 = ggplot(data = data1, aes(x= Main_Cat, y= Percentage,  fill= Sub_Cat)) + # don't change these
  geom_bar(position = position_stack(), stat="identity", width = 1) + # don't change these
  ggtitle("title") +  # title text 
  theme(plot.title = element_text(hjust = 0.5, size=14, face = "bold")) +
  xlab("All Categories") + # x axis text
  ylab("Percentage (%)") + # y axis text
  geom_text(aes(label = Percentage), position = position_stack(vjust = 0.5), size = 4.6) + # number labels on graph
  theme(panel.background = element_blank()) + # background colour
  theme(axis.line = element_line(colour = "black")) + # axis colour
  scale_y_continuous(expand = c(0,0)) + scale_x_discrete(expand = c(1,1)) + # change position of axis
  theme(axis.text=element_text(size=12, face = "bold", colour = "black"), 
        axis.title=element_text(size=14,face="bold", colour = "black")) + # axis settings
  scale_fill_manual(values = c("#FFFF00", "#98FB98", "#00BFFF", "#0000FF")) + #change colours
  theme(axis.line.x = element_line("white")) 


print(Plot1)

Plot image

我想将条形图移近 y 轴或将 y 轴移近条形而不改变条形本身的宽度。

有什么建议吗?

【问题讨论】:

  • 您能提供“data1”或它的一小部分以便能够使用您提供的代码吗?
  • 请使用此参考来生成相同的t-redactyl.io/blog/2016/01/…
  • 嗨@Dave,我创建了一个示例数据集以与以下代码一起使用:Main_Cat = c("All") Sub_Cat = c("A", "B", "C", "D ") 百分比 = c(4, 5, 67, 24) data1 = data.frame(Main_Cat, Sub_Cat, Percentage)

标签: r ggplot2 stacked-chart


【解决方案1】:

这里有一些事情需要考虑,您可以使用它们来获得您想要的情节。即,我将使用以下方法来调整 y 轴相对于条形的位置:

  1. 知道保存图像的输出与图形设备的分辨率和纵横比有关。换句话说,如果您调整图形窗口的大小,您会得到不同的绘图。这也会溢出到ggsave()(或者您正在保存图像)。您可以通过调整ggsave()函数中的height=width=来控制输出。

  2. 您的geom_barwidth=。您已在代码中将其设置为 width=1,但您可以使用它来压缩或扩展您的条形图。如果您只有一个条,请随意超过 1,但如果您有多个条,width=1.5 会溢出到下一个轴值...不确定这对您来说是否是个问题,但如果不是这可能是一种让酒吧更近的笨拙方式。

  3. 让距离更近的最佳方法是使用scale_x_discrete()expand= 参数。你已经用过这种……那种。检查函数的文档,其中提到您应该使用expansion() 函数来设置expand=。它可以设置 expand=c(0,0) 以删除绘图周围的所有扩展 - 这就是为什么你的 y 轴没有扩展 - 但如果你只是将向量传递给 expand= 参数,则同样不成立。您应该将其设置为expand=expansion(),然后在expansion() 内您需要传递mult=add=

你可以调整你想要的方式,但这是我用来在下面创建两个示例的代码。

将轴设置在条形旁边

# use the entire code you already posted, except change only the line below:
scale_x_discrete(expand = expansion(add=c(0,0)))
print(Plot1)

# remember, important to set the width/height
ggsave('example_1.png', width=2.5,height=5)

(抱歉,此页面上的图片很大,但您可以调整大小...)

在轴和条形之间添加一点空间(但只是一点点)

# same as before, but your line now reads something like
scale_x_discrete(expand = expansion(add=c(0.6,0.5)))
print(Plot1)

ggsave('example_1.png', width=2.5,height=5)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-18
    • 2019-05-19
    • 1970-01-01
    • 2021-12-08
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多