ggplot在python中的使用(plotnine)


plt中的中文亂碼解決:

plt.rcParams['font.sans-serif']=['SimHei'] #用來正常顯示中文標簽
plt.rcParams['axes.unicode_minus']=False #用來正常顯示負號

條形圖:

注意中文亂碼

from plotnine import *
import pandas as pd

median_age_dict={
    '國家': ['New Zealand','Spain','Ireland','Israel','Denmark','Norway','Netherlands','Australia','Italy','Sweden'],
    '年齡': [39.0, 37.0, 35.0, 34.0, 34.0, 34.0, 34.0, 34.0, 34.0, 34.0]
}
median_age=pd.DataFrame(median_age_dict)

(
#     fill以顏色區分
ggplot(median_age,aes(x='國家',y='年齡',fill='國家'))
#     條形圖,需要stat指明統計量
    +geom_bar(stat='identity',width=0.5)
#     文本標簽,nudge_y表示偏離量
    +geom_text(aes(x='國家',y='年齡',label='年齡'),nudge_y=2)
    +coord_flip()# 翻轉x,y
#     排序條形圖
    +xlim(median_age['國家'])
#     +xlim(median_age['Country'][::-1])逆序
#     隱藏圖例,設置中文字體
    +theme(legend_position = 'none',text=element_text(family='KaiTi'))
#     加上標題
    +ggtitle('Top 10 Median age of respondents from different countries')
)

 

 

 折線圖:

這里我比較喜歡日期的間距設置

from plotnine.data import economics
save_rate = economics[economics['date']>'2013-01-01']
save_rate=save_rate.reset_index(drop=True)
(
ggplot(save_rate,aes(x='date',y='psavert'))
+ geom_line(color='blue')
+geom_point(color='red')
+ ylim(0,6)#y軸的范圍
#     改變x坐標刻度間距
+ scale_x_date(breaks='5 months',date_labels='%Y-%m')
)

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM