是否可以在R中设置条形图的颜色范围?

f87krz0w  于 2023-05-04  发布在  其他
关注(0)|答案(2)|浏览(192)

我是R的初学者,我有一个2列的dataframe,第一列包含每个分析的标题,第二列包含6.7到14之间的值。我需要做一个像这样的条形图

我的数据框名为FEA:

Tit   lp 
hsa05225 14.0  
hsa05165 12.0  
hsa05200 10.0  
hsa05163  9.2  
GO:0045785  8.8   
hsa04550  8.5   
GO:0022409  8.3   
hsa04218  8.3   
hsa05213  8.2   
hsa04115  7.8   
GO:0010720  7.6   
GO:0022407  7.2  
GO:1902532  6.9

我使用了这个代码:

colnames(FEA)<-c("Tit","lp")
FEA$Row<-c(13:1)
    ggplot(FEA,aes(Row,lp,fill=Tit))+ geom_bar(stat = "identity")+ coord_flip()+
      scale_x_discrete(name="") +
 scale_y_continuous(breaks=c(0,2,4,6,8,10,12,14,16,18),expand = c(0,0),limits = c(0,15))+ 
labs(y= "-log10(P)") +theme(legend.title=element_blank())+ scale_color_discrete(name="")+ theme_bw()

但我需要在每个酒吧前面显示图例,并将颜色从红色改为黄色,如果可能的话,还可以在酒吧后面添加垂直线。

0dxa2lsx

0dxa2lsx1#

像这样的?
您可以手动更改条形图的颜色。

library(readr) # for reading your sample data
library(ggplot2)
library(ggthemes) # for theme_few()

ggplot(df, aes(x=reorder(Tit,lp), y=lp, fill=lp))+
  geom_hline(yintercept = c(2,4,6,10), color="lightgrey")+
  geom_bar(stat="identity", color="black", width=.8) +
  coord_flip()+
  scale_fill_gradient(low="#FFE06F", high = "#DD6602") +
  scale_y_continuous(breaks=c(0,2,4,6,8,10,12,14,16,18),
                     expand = c(0,0),
                     limits = c(0,15))+ 
  scale_x_discrete(position="top", expand=c(0.08,0.08))+
  labs(y= "-log10(P)", x="") + 
  theme_few() +
  theme(legend.position = "none")

创建于2023-04-27带有reprex v2.0.2

oknwwptz

oknwwptz2#

我们可以这样做:

library(ggplot2)
library(dplyr)
library(forcats)

colors <- colorRampPalette(c("red", "yellow"))(length(unique(FEA$Tit)))

FEA %>% 
  mutate(Row = rev(row_number()),
         colors = colorRampPalette(c("red", "yellow"))(length(unique(FEA$Tit)))
         ) %>% 
  ggplot(aes(Row,lp,fill=fct_inorder(Tit)))+ 
  geom_bar(stat = "identity")+ 
  scale_fill_manual(values = colors) +
  coord_flip()+
  scale_x_discrete(name="") +
  scale_y_continuous(breaks=c(0,2,4,6,8,10,12,14,16,18),expand = c(0,0),limits = c(0,15))+ 
  labs(y= "-log10(P)") +
  theme(legend.title=element_blank())+ scale_color_discrete(name="")+ 
  theme_bw()

相关问题