繁体   English   中英

ggplot2堆叠的barplot大小和颜色

[英]ggplot2 stacked barplot size & color

这些可能是一些简单的问题,但是我正在学习。 我将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种以上的颜色。

我找到了一些解决方案,以使图更具吸引力并自行调整尺寸:

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)

因此大部分仍然是关于颜色矢量的问题

如果要使用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软件包。 看到这个答案

暂无
暂无

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

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