【问题标题】:Use small font with ggplot2在 ggplot2 中使用小字体
【发布时间】:2020-09-23 11:20:24
【问题描述】:

我尝试用 ggplot 制作情节。因此,在 R-Studio 中绘图时,evereting 是可以的。但是,当我尝试制作 PDF 并将此图从 R 输出到外部时,就会出现问题。即字母自身重叠。你可以在下面的图片中看到,我已经用黄色标记了。

为了绘图,我使用这行代码

# Plotting with ggplot2
        p<-ggplot(data_plot, aes(x=y, y=z)) +
           stat_pareto(point.color = "red",
                      point.size = 3,
                      line.color = "black",
                      size.line = 1,
                      bars.fill = c("blue", "orange")
          ) +
          xlab(' ') +
          ylab('')
        
       # Output in pdf
        pdf(file=paste("out.pdf",sep=""),width=10, height=5)
        
        op <- par(mgp=c(1,0,0),mar=c(2, 2, 1, 1),# Room for the title and legend: 1_bottom,2_left,3_up,4_right
                  mfrow=c(1,2))
        
        plot(p)

那么任何人都可以帮助以获得更好的 x 轴值、较小字体的字母或其他任何东西并修复此错误吗?

【问题讨论】:

  • 您可以将+ theme(text=element_text(family = "serif", size=10), axis.text.x = element_text(angle=45, vjust=0.5, colour="black"), axis.text.y = element_text(colour="black")) 添加到您的代码中以旋转x 轴标题。
  • 另外,您可以增加 pdf 的宽度和高度。结果文字会变小。
  • 您可以使用+ theme(axis.text.x = element.text(size = a_very_small_number)) 调整字体大小,然后使用ggplot2::ggsave() 将您的绘图保存为pdf。在保持良好的比例方面,我通常发现它比 pdf() 更容易做到。
  • 当你有这么多条形图时,一个合理的选择是制作水平条形图。每个条都是水平的,但条是垂直列出的。并且条形标签不会相互重叠。

标签: r pdf ggplot2


【解决方案1】:

最新版本的 ggplot 允许您通过在 guide_axis 中指定 n.dodge 来避开轴标签,以修复重叠的 x 轴标签。

比较这个情节:

library(ggplot2)

p <- ggplot(data.frame(y = 1/1:10, x = paste("long label", 0:9)), aes(x, y)) +
      geom_col(fill = "royalblue")
p

到这里:

p + scale_x_discrete(guide = guide_axis(n.dodge = 2))

【讨论】:

    【解决方案2】:

    请在下面找到一些在处理字体大小时对我有很大帮助的想法。在尝试了很多基本绘图系统之后,我总是回到 ggplot 及其强大的 theme()ggsave() 函数。你正在用 ggplot 制作你的情节,为什么不坚持到最后呢? ;)

    library(ggplot2)
    
    ggplot(data = iris, aes(x = Species, y = Sepal.Width)) +
      geom_bar(stat = "identity") +
      theme(axis.text.x = element_text(size = 4)) # change here the size of the text
    
    ggsave(filename = "test.pdf", device = "pdf", width = 5, height = 5, units = "cm", dpi = 500) # use this function to save your plot
    # much easier to control end dimensions and resolution.
    # Here I plot a 5cm x 5 cm plot with font size of 4 pt on x-axis labels
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-12
      • 2021-04-20
      • 2015-07-15
      • 2013-12-22
      • 2023-04-06
      • 2019-06-05
      • 2021-04-30
      • 2012-08-10
      相关资源
      最近更新 更多