如何在ggplot中为R改变条形图

时间:2014-06-27 16:09:42

标签: r plot ggplot2 lattice

我在ggplot中有一个情节,向我展示了每个“评级”类别“银行”和“系统”中的价格水平。这是我的代码:

##fict
a<-c("rating1","rating2","rating3")
b<-c(1.2,1.2,1.3)
c<-c(1.6,1.4,1.6)

gg<-cbind('rating'=rep(a,2),'price'=c(b,c),'tipo'=rep(c("bank","sistem"),3))
gg<-as.data.frame(gg)


a<-rgb(red=150, green=191, blue=37, maxColorValue = 255)
b<-rgb(red=80, green=113, blue=14, maxColorValue = 255)


    ggplot(gg, aes(x=tipo, y=price,width=1)) +   
      geom_bar(position='stack', stat='identity', fill=c(b,a), color='black') +
      facet_wrap( ~ rating)+
      theme_bw() +  theme(axis.line = element_line(colour = "black"),
         panel.grid.major = element_blank(),
       panel.grid.minor = element_blank(),
       panel.border = element_blank(),
       panel.background = element_blank(),
    strip.background = element_rect(colour = 'white', fill = 'white', size = 3),
    axis.title.y=element_text(vjust=0.19),
    axis.title.x=element_text(vjust=0.19)
    #strip.text.x = element_text(colour = 'red', angle = 45, size = 10, hjust = 0.5, vjust = 0.5, face = 'bold')
    ) + xlab("My x label") +
      ylab("My y label") +
    labs(title = 'difference')

此代码生成我的情节。

我想改变三件事:

  • 我希望标签评级显示在底部
  • 我希望“银行”和“系统”标签消失,并用带有银行和系统颜色的图例进行更改。
  • 如果可能也将图例放在x轴标题下水平方式

谢谢

1 个答案:

答案 0 :(得分:1)

将评论升级为答案。

library(ggplot2)

# your data - tweaked the code - there is no need to cbind within data.frame
# and names do not need to be in quotes
gg <- data.frame(rating=rep(c("rating1","rating2","rating3"),2),
                 price=c(c(1.2,1.2,1.3),c(1.6,1.4,1.6)),
                 tipo=rep(c("bank","sistem"),3))

a <- rgb(red=150, green=191, blue=37, maxColorValue = 255)
b <- rgb(red=80, green=113, blue=14, maxColorValue = 255)

# Plot

# use position dodge to get the bars side-by-side
# theme_classic removes grid lines and uses theme_bw()
# scale_fill_manual to manually specify the colours - by using fill = tipo in the 
# aesthetic call of ggplot a legend will be generated
# scale_y_continuous - using expand starts the axis at exactly zero


ggplot(gg, aes(x=rating, y=price, fill=tipo)) +   
  geom_bar(position='dodge', stat='identity', color='black') +
  theme_classic() + 
  scale_fill_manual(values = c(b,a)) +
  scale_y_continuous(limit=c(0,2), expand=c(0,0)) +
  labs(title = 'difference', x = "My x label", y = "My y label") +
  theme(
      axis.title.y=element_text(vjust=0.19),
      axis.title.x=element_text(vjust=0.19) ,
      legend.position = "bottom",
      legend.title=element_blank())  

enter image description here