【问题标题】:ggplot2 stacked barplot size & colorggplot2 堆叠条形图大小和颜色
【发布时间】:2018-03-14 14:52:31
【问题描述】:

这些可能是一些简单的问题,但我正在学习。 我正在将 ggplot2 用于堆叠条形图,并且我想出了如何以基本形式做到这一点:

df<- data
stack <-ggplot(df,aes(x=group, y=average.contribution, fill=taxa)) + 
          geom_bar(stat="identity")

(dataset with bacterial abundance)

但我在调整绘图大小时遇到​​问题,我找不到好的例子(可能是theme())。

特别是:

  1. 定义绘图的大小(例如 5cm x 5 cm)
  2. 定义条的宽度
  3. 轴标签到轴的距离
  4. 绘图中使用的字体
  5. 定义图例的大小

我可以使用scale_fill_brewer() 中的各种主题的颜色矢量吗?我需要超过 7 种颜色。

【问题讨论】:

标签: r ggplot2


【解决方案1】:

当您想要超过 7 种颜色时,您有多种选择:

# your plot code as a starting point
stck <- ggplot(df,aes(x= group, y=average.contribution, fill=taxa)) + 
  geom_bar(stat="identity", width=.7) + 
  facet_grid(. ~ fac) + 
  scale_y_continuous(limits=c(0,100)) + 
  theme(panel.grid.minor.x=element_blank(), panel.grid.major.x=element_blank()) + 
  theme_bw()

您可以选择手动设置颜色:

# manually with color names
stck + scale_colour_manual(values=c("red", "blue")) # 2 colors as example, add as many as you need

# manually with RGB values
stck + scale_colour_manual(values=c("#CC6666", "#7777DD"))

您也可以使用RColorBrewer 包:

library(RColorBrewer)
display.brewer.all() # shows the different palettes you can choose from

stck + scale_fill_brewer(palette="Set3") # a color palette with 12 colors

要更改轴标签到轴的距离,您至少有两种选择:

# inserting blank lines with \n
stck + xlab("\nLabel")

# vertically or horizontally adjusting the label
stck + theme(axis.text.x = element_text(hjust=-1, vjust=-1)) # ylab -> hjust; xlab -> vjust

用于改变文本的外观:

element_text(size=14, face="bold", color="red", family = "sans")

当您想使用特定字体时,可以安装extrafont 包。见this answer

【讨论】:

    【解决方案2】:

    我找到了一些解决方案,让情节更有吸引力,并自己调整大小:

    df<-so2
    stack<-ggplot(df,aes(x= group, y=average.contribution, fill=taxa)) 
    + geom_bar(stat="identity", width=.7) 
    + facet_grid(. ~ fac) +scale_y_continuous(limits=c(0,100)) 
    + theme(panel.grid.minor.x=element_blank(), panel.grid.major.x=element_blank()) 
    + theme_bw() 
    
    ggsave(stack, file="stack.pdf", width=10, height=10)
    

    因此主要是关于颜色向量的问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-25
      • 2023-04-09
      • 2018-09-30
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多