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圖片20180712220000.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:突然想到之前遇到的一個問題找到了解決辦法,明天(20180702)來補充;找資料還找到了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
結果就變成了這樣
參考文章
總結
以上是生活随笔為你收集整理的ggplot绘制柱状图 python_ggplot2堆积柱形图笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: openmv 图像一维数组_第N维数组和
- 下一篇: 在三星应用商店提交的应用程序, 可以不包