900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > ggplot绘制柱状图 python_ggplot2堆积柱形图笔记

ggplot绘制柱状图 python_ggplot2堆积柱形图笔记

时间:2021-01-21 21:10:57

相关推荐

ggplot绘制柱状图 python_ggplot2堆积柱形图笔记

#creat a dataset(生成数据)

specie

condition

value

df

library(ggplot2)

#分组柱形图

p1

p1+theme(legend.position = "none")#去掉右侧图例

p1+scale_fill_manual(values=c("blue","red","green"))#自定义填充色

Rplot09.png

Rplot10.png

Rplot11.png

#堆积柱形图

ggplot(df,aes(x=specie,y=value,fill=condition))+geom_bar(stat="identity")

ggplot(df,aes(x=specie,y=value,fill=condition))+

geom_bar(stat="identity")+

geom_text(aes(label=value),position=position_stack(vjust=0.5))#添加标签

可以比较一下一下三条命令出图的区别

ggplot(df,aes(x=specie,y=value,fill=condition))+

geom_bar(stat="identity")+

geom_text(aes(label=value))#1

ggplot(df,aes(x=specie,y=value,fill=condition))+

geom_bar(stat="identity")+

geom_text(aes(label=value),position=position_stack())#2 position_stack()参数用来调整添加的标签和每部分堆积柱子相匹配,默认应该是添加到每部分顶端

ggplot(df,aes(x=specie,y=value,fill=condition))+

geom_bar(stat="identity")+

geom_text(aes(label=value),position=position_stack(vjust=0.5))#3 vjust参数用来调整标签的为重,vjust=0.5将标签放到对应部位的中部

Rplot12.png

Rplot13.png

Rplot14.png

Rplot15.png

基本的堆积柱形图应该做完了,接下来模仿这张图片

QQ图片0712220000.jpg

暂时只想到一种解决办法,更改数据格式,把之前用到的df数据集改成这样:添加两列用来指定文本和标签的位置

更改后的数据集

ggplot(df,aes(x=specie,y=value,fill=condition))+

geom_bar(stat="identity")+

geom_text(aes(label=specie,y=var4))+ylim(-20,65)+#设置纵坐标范围以掩盖多余的标签

geom_label(aes(label=value,y=var5))+theme_bw()+

theme(axis.text.x = element_blank(),#去除横坐标轴标签

axis.ticks.x = element_blank(),#去除横坐标刻度

axis.line.x = element_blank(),

panel.border = element_blank(),#去掉边框

axis.ticks.y = element_blank(),#去掉纵坐标刻度

legend.position="none")#去掉图例

效果基本满意

PS:突然想到之前遇到的一个问题找到了解决办法,明天(0702)来补充;找资料还找到了python绘制堆积柱形图的代码,明天也重复一下。有些困了,睡觉

更新

#完全重复其代码

setwd("Rpractice/kaggle_practice_data/Kobe_shot_selection/")

df

train

names(train)

train$shot_made_flag

ggplot(train,aes(x=season,fill=shot_made_flag))+geom_bar(stat="count",position="fill")+

scale_fill_manual(values=c("red","blue"))+

theme(axis.text.x = element_text(angle=90,vjust=0.5))#将横坐标标签调整为垂直,vjust 轻微调整位置

scale_fill_brewer(palette="Set1",direction=-1)#填充颜色

Rplot07.png

重复里面的堆积柱形图时遇到的问题:如果我想让上半部分红色与下半部分蓝色互换位置应该怎么办,答案:将代码一换成代码二

train$shot_made_flag

train$shot_made_flag

结果就变成了这样

参考文章

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。