栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

类别比较型图表

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

类别比较型图表

1、柱形图

柱状图是离散时间数据可视化的方式之一,只不过这里的系列值的数据类型是「时间」而已。
柱状图除了可以用于离散时间数据的可视化,更多的是用于比较不同分类数据的可视化,且柱状图的数据条数,最好不要超过12条。

单数据系列柱形图:
import pandas as pd
import numpy as np
from plotnine import *

mydata=pd.DataFrame({'Cut':["Fair","Good","Very Good","Premium","Ideal"],
                     'Price':[4300,3800,3950,4700,3500]})
Sort_data=mydata.sort_values(by='Price', ascending=False)
#Sort_data['Cut']=Sort_data['Cut'].astype("category",categories=Sort_data['Cut'],ordered=True)
Sort_data['Cut']=pd.Categorical(Sort_data['Cut'],ordered=True, categories=Sort_data['Cut'])

base_plot=(ggplot(Sort_data,aes('Cut','Price'))
+geom_bar(stat = "identity", width = 0.8,colour="black",size=0.25,fill="#FC4E07",alpha=1)  
+ylim(0, 6000)
+theme(
       axis_title=element_text(size=18,face="plain",color="black"),
       axis_text = element_text(size=16,face="plain",color="black"),
       aspect_ratio =1.15,
       figure_size = (6.5, 6.5),
       dpi = 50
       )
)
print(base_plot)

多数据系列柱形图:
import pandas as pd
import numpy as np
from plotnine import *

df=pd.read_csv('MultiColumn_Data.csv')
df=df.sort_values(by='1996', ascending=False)
mydata=pd.melt(df, id_vars='Catergory')

mydata['Catergory']=pd.Categorical(mydata['Catergory'],ordered=True, categories=df['Catergory'])

base_plot=(ggplot(mydata,aes(x='Catergory',y='value',fill='variable'))
+geom_bar(stat="identity", color="black", position='dodge',width=0.7,size=0.25)
+scale_fill_manual(values=["#00AFBB", "#FC4E07", "#E7B800"])
+ylim(0, 10)
+theme(legend_title=element_text(size=18,face="plain",color="black"),
       legend_text=element_text(size=16,face="plain",color="black"),
       axis_title=element_text(size=18,face="plain",color="black"),
       axis_text = element_text(size=16,face="plain",color="black"),
       legend_background=element_blank(),
       legend_position=(0.75,0.80),
       aspect_ratio =1.15,
       figure_size = (6.5, 6.5),
       dpi = 50
       )
)
print(base_plot)

堆积柱形图:
import pandas as pd
import numpy as np
from plotnine import *

df=pd.read_csv('StackedColumn_Data.csv')
Sum_df=df.iloc[:,1:].apply(lambda x: x.sum(), axis=0).sort_values(ascending=False)
meanRow_df=df.iloc[:,1:].apply(lambda x: x.mean(), axis=1)
Sing_df=df['Clarity'][meanRow_df.sort_values(ascending=True).index]
mydata=pd.melt(df,id_vars='Clarity')

mydata['variable']=mydata['variable'].astype("category")
mydata['Clarity']=mydata['Clarity'].astype("category")
base_plot=(ggplot(mydata,aes(x='variable',y='value',fill='Clarity'))
+geom_bar(stat="identity", color="black", position='stack',width=0.7,size=0.25)
+scale_fill_brewer(palette="YlOrRd")
+ylim(0, 15000)
+theme(
       legend_title=element_text(size=18,face="plain",color="black"),
       legend_text=element_text(size=16,face="plain",color="black"),
       axis_title=element_text(size=18,face="plain",color="black"),
       axis_text = element_text(size=16,face="plain",color="black"),
       legend_background=element_blank(),
       legend_position=(0.75,0.75),
       aspect_ratio =1.15,
       figure_size = (6.5, 6.5),
       dpi = 50
       ))
print(base_plot)

百分比堆积柱形图:
import pandas as pd
import numpy as np
from plotnine import *

df=pd.read_csv('StackedColumn_Data.csv')
SumCol_df=df.iloc[:,1:].apply(lambda x: x.sum(), axis=0)
df.iloc[:,1:]=df.iloc[:,1:].apply(lambda x: x/SumCol_df, axis=1)
meanRow_df=df.iloc[:,1:].apply(lambda x: x.mean(), axis=1)
Per_df=df.iloc[meanRow_df.idxmax(),1:].sort_values(ascending=False)
Sing_df=df['Clarity'][meanRow_df.sort_values(ascending=True).index]
mydata=pd.melt(df,id_vars='Clarity')
mydata['Clarity']=mydata['Clarity'].astype("category")
mydata['variable']=mydata['variable'].astype("category")

base_plot=(ggplot(mydata,aes(x='variable',y='value',fill='Clarity'))
+geom_bar(stat="identity", color="black", position='fill',width=0.7,size=0.25)
+scale_fill_brewer(palette="GnBu")
#+ylim(0, 10)
+theme(
       #text=element_text(size=15,face="plain",color="black"),
       legend_title=element_text(size=18,face="plain",color="black"),
       legend_text=element_text(size=16,face="plain",color="black"),
       axis_title=element_text(size=18,face="plain",color="black"),
       axis_text = element_text(size=16,face="plain",color="black"),
       aspect_ratio =1.15,
       figure_size = (6.5, 6.5),
       dpi = 50
       ))
print(base_plot)

2、条形图

条形图,可以视为是柱状图的一种变体,在大部分情况下,是可以互换的。条形图,相比柱状图而言,可以展示更多的数据条数,一般不要超过30条。
若分类项的文本过长时,柱状图的文本需要进行旋转才能不重叠,不利于阅读,而条形图就就没有这个缺点。

单数据系列条形图:
import pandas as pd
import numpy as np
from plotnine import *

import matplotlib.pyplot as plt 
df=df.iloc[:,[0,2,1]]
df=df.sort_values(by='Pensions', ascending=True)
mydata=pd.melt(df,id_vars='Country')

mydata['Country']=mydata['Country'].astype("category")
base_plot=(ggplot(mydata,aes('Country','value',fill='variable'))+
  geom_bar(stat="identity", color="black", position=position_dodge(),width=0.7,size=0.25)+
  scale_fill_manual(values=("#00AFBB", "#FC4E07", "#E7B800"))+
  coord_flip()+
  theme(
    axis_title=element_text(size=15,face="plain",color="black"),
    axis_text = element_text(size=12,face="plain",color="black"),
    legend_title=element_text(size=14,face="plain",color="black"),
    legend_background  =element_blank(),
    legend_position = (0.8,0.2),
    aspect_ratio =1.15,
    figure_size = (6.5, 6.5),
     dpi = 50
  ))
print(base_plot)

多数据系列条形图:
import pandas as pd
import numpy as np
from plotnine import *

import matplotlib.pyplot as plt 
df=pd.read_csv('Stackedbar_Data.csv')
Sum_df=df.iloc[:,1:].apply(lambda x: x.sum(), axis=0).sort_values(ascending=True)
meanRow_df=df.iloc[:,1:].apply(lambda x: x.mean(), axis=1)
Sing_df=df['Country'][meanRow_df.sort_values(ascending=True).index]
mydata=pd.melt(df,id_vars='Country')
mydata['variable']=mydata['variable'].astype("category")
mydata['Country']=mydata['Country'].astype("category")

base_plot=(ggplot(mydata,aes('Country','value',fill='variable'))+
  geom_bar(stat="identity", color="black", position='stack',width=0.65,size=0.25)+
  scale_fill_brewer(palette="YlOrRd")+
  coord_flip()+
  theme(
    axis_title=element_text(size=18,face="plain",color="black"),
       axis_text = element_text(size=16,face="plain",color="black"),
       legend_title=element_text(size=18,face="plain",color="black"),
       legend_text = element_text(size=16,face="plain",color="black"),
    legend_background  =element_blank(),
    legend_position = 'right',
    aspect_ratio =1.15,
    figure_size = (6.5, 6.5),
     dpi = 50
  ))
print(base_plot)

百分比堆积条形图:
import pandas as pd
import numpy as np
from plotnine import *

import matplotlib.pyplot as plt
df=pd.read_csv('Stackedbar_Data.csv')
SumCol_df=df.iloc[:,1:].apply(lambda x: x.sum(), axis=1)
df.iloc[:,1:]=df.iloc[:,1:].apply(lambda x: x/SumCol_df, axis=0)

meanRow_df=df.iloc[:,1:].apply(lambda x: x.mean(), axis=0).sort_values(ascending=True)
Per_df=df.loc[:,meanRow_df.idxmax()].sort_values(ascending=True)
Sing_df=df['Country'][Per_df.index]
mydata=pd.melt(df,id_vars='Country')
mydata['Country']=mydata['Country'].astype("category")
mydata['variable']=mydata['variable'].astype("category")

base_plot=(ggplot(mydata,aes(x='Country',y='value',fill='variable'))
+geom_bar(stat="identity", color="black", position='fill',width=0.7,size=0.25)
+scale_fill_brewer(palette="GnBu")
+coord_flip()
+theme(
       #text=element_text(size=15,face="plain",color="black"),
       axis_title=element_text(size=18,face="plain",color="black"),
       axis_text = element_text(size=16,face="plain",color="black"),
       legend_title=element_text(size=18,face="plain",color="black"),
       legend_text = element_text(size=16,face="plain",color="black"),
       aspect_ratio =1.15,
       figure_size = (6.5, 6.5),
       dpi = 50
       ))
print(base_plot)

3、不等宽柱形图

不等宽柱形图顾名思义就是宽度不等的柱形图,这样将相关联的两类数据通过宽度不等的柱形图排列在一起,可以轻轻松松帮助我们简单直观地比较两个不同信息,从而帮助我们发现问题和解决问题。

多数据系列:
import pandas as pd
import numpy as np
from plotnine import *

mydata=pd.DataFrame(dict(Name=['A','B','C','D','E'],
                         Scale=[35,30,20,10,5],
                         ARPU=[56,37,63,57,59]))
#构造矩形X轴的起点(最小点)
mydata['xmin']=0
for i in range(1,5):
    mydata['xmin'][i]=np.sum(mydata['Scale'][0:i])
    
#构造矩形X轴的终点(最大点)
mydata['xmax']=0
for i in range(0,5):
    mydata['xmax'][i]=np.sum(mydata['Scale'][0:i+1])
mydata['label']=0
for i in range(0,5):
 mydata['label'][i]=np.sum(mydata['Scale'][0:i+1])-mydata['Scale'][i]/2
base_plot=(ggplot(mydata)+ geom_rect(aes(xmin='xmin',xmax='xmax',ymin=0,ymax='ARPU',fill='Name'),colour="black",size=0.25)+
geom_text(aes(x='label',y='ARPU+3',label='ARPU'),size=14,color="black")+
  geom_text(aes(x='label',y=-4,label='Name'),size=14,color="black")+
  scale_fill_hue(s = 0.90, l = 0.65, h=0.0417,color_space='husl')+
  ylab("ARPU")+
  xlab("scale")+
  ylim(-5,80)+
  theme(#panel_background=element_rect(fill="white"),
        #panel_grid_major = element_line(colour = "grey",size=.25,linetype ="dotted" ),
        #panel_grid_minor = element_line(colour = "grey",size=.25,linetype ="dotted" ),
        text=element_text(size=15),
        legend_position="none",
        aspect_ratio =1.15,
        figure_size = (5, 5),
        dpi = 100
  ))
print(base_plot)

4、作棒棒糖图、克利夫兰点图、哑铃图

棒棒糖图因其形状和棒棒糖相似而得名,具体来看实际上是一个散点和一条线段的组合。棒棒糖图是散点图的一种变体,又与柱状图非常相似,但其在清晰展示数据的同时,减少了图形量,使得读者能够更加关注于数据本身而非图形。棒棒糖图能够帮助将数值与类别对齐,非常适合比较多个类别的值之间的差异。
克利夫兰点图,类似棒棒糖图,只是没有连接的线条,重点强调数据的排序展示及互相之间的差距。克利夫兰点图一般都横向展示,所以 Y 轴变量一般为类别型变量。只需使用geom_point()即可绘制克利夫兰点图。
哑铃图可以看成多数据系列的克利夫兰点图,只是使用直线连接了两个数据系列的数据点。哑铃图主要用于:
①展示在同一时间段两个数据点的相对位置(增加或者减少);
②比较两个类别之间的数据值差别。

import pandas as pd
import numpy as np
from plotnine import *
from plotnine.data import *
import matplotlib.pyplot as plt

df=pd.read_csv('DotPlots_Data.csv')
df['sum']=df.iloc[:,1:3].apply(np.sum,axis=1)
df=df.sort_values(by='sum', ascending=True)
df['City']=df['City'].astype("category")
#棒棒糖图
base_plot=(ggplot(df, aes('sum', 'City')) +
  geom_segment(aes(x=0, xend='sum',y='City',yend='City'))+
  geom_point(shape='o',size=3,colour="black",fill="#FC4E07")+
  theme(
    axis_title=element_text(size=12,face="plain",color="black"),
    axis_text = element_text(size=10,face="plain",color="black"),
    #legend_title=element_text(size=14,face="plain",color="black"),
   aspect_ratio =1.25,
    figure_size = (4, 4),
     dpi = 100
  ))
print(base_plot)
#克利夫兰点图
base_plot=(ggplot(df, aes('sum', 'City')) +
  geom_point(shape='o',size=3,colour="black",fill="#FC4E07")+
  theme(
    axis_title=element_text(size=12,face="plain",color="black"),
axis_text = element_text(size=10,face="plain",color="black"),
aspect_ratio =1.25,
    figure_size = (4, 4),
     dpi = 100
  ))
print(base_plot)

import pandas as pd
import numpy as np
from plotnine import *
from plotnine.data import *
import matplotlib.pyplot as plt

df=pd.read_csv('DotPlots_Data.csv')
df['sum']=df.iloc[:,1:3].apply(np.sum,axis=1)
df=df.sort_values(by='sum', ascending=True)
df['City']=df['City'].astype("category")
#克利夫兰点图
base_plot=(ggplot(df, aes('sum', 'City')) +
  geom_point(shape='o',size=3,colour="black",fill="#FC4E07")+
  theme(
    axis_title=element_text(size=12,face="plain",color="black"),
axis_text = element_text(size=10,face="plain",color="black"),
aspect_ratio =1.25,
    figure_size = (4, 4),
     dpi = 100
  ))
print(base_plot)
    

import pandas as pd
import numpy as np
from plotnine import *
from plotnine.data import *
import matplotlib.pyplot as plt 
df=pd.read_csv('DotPlots_Data.csv')
df=df.sort_values(by='Female', ascending=True)
df['City']=df['City'].astype("category")
mydata=pd.melt(df,id_vars='City')
#哑铃图
base_plot=(ggplot(mydata, aes('value','City',fill='variable')) +
  geom_line(aes(group = 'City')) +
   geom_point(shape='o',size=3,colour="black")+
  scale_fill_manual(values=("#00AFBB", "#FC4E07","#36BED9"))+
  theme(
    axis_title=element_text(size=13,face="plain",color="black"),
    axis_text = element_text(size=10,face="plain",color="black"),
    legend_title=element_text(size=12,face="plain",color="black"),
    legend_text = element_text(size=10,face="plain",color="black"),
    legend_background = element_blank(),
    legend_position = (0.75,0.2),
  aspect_ratio =1.25,
    figure_size = (4, 4),
     dpi = 100
  ))
print(base_plot)

5、坡度图:两年份对比、多年份对比。

坡度图是表示地面倾斜率的地图。主要用晕线或颜色在图上直接表示出坡度的大小或陡缓。坡度倾角(α)的计算公式是:
tgα=h/l
式中h表示高差,l表示水平距离。坡度数值的形式,通常用一个倾斜面对水平面间的夹角,即倾斜角度表示;也有用地面比降分数式或百分率表示。编制坡度图要借助于带有等高线的地形图,一般大比例尺图图廓下方多附有坡度尺,可用其所标示的各级坡度值所相应的等高线之间的水平距,量出各级坡度。实际作图时,往往用等高线密度尺在地形图上进行坡度分级。其分级标准,多根据人们改造和利用自然实际需要的坡度临界极限,或各地貌类型自然界限值进行确定。坡度图对农业、林业、水利建设及军事等方面均有重要实用价值。

#5-1 坡度图两年份对比
import pandas as pd
import numpy as np
from plotnine import *
df=pd.read_csv('Slopecharts_Data1.csv')

left_label=df.apply(lambda x: x['Contry']+','+ str(x['1970']),axis=1)
right_label=df.apply(lambda x: x['Contry']+','+ str(x['1979']),axis=1)
df['class']=df.apply(lambda x: "red" if x['1979']-x['1970']<0 else "green",axis=1)

#list(map(lambda x,y:"red" if x-y<0 else "green", left_label,right_label))

base_plot=(ggplot(df) + 
  geom_segment(aes(x=1, xend=2, y='1970', yend='1979', color='class'), size=.75, show_legend=False) +  #连接线
  geom_vline(xintercept=1, linetype="solid", size=.1) + # 1952年的垂直直线
  geom_vline(xintercept=2, linetype="solid", size=.1) + # 1957年的垂直直线
  geom_point(aes(x=1, y='1970'), size=3,shape='o',fill="grey",color="red") + # 1952年的数据点
  geom_point(aes(x=2, y='1979'), size=3,shape='o',fill="grey",color="red") + # 1957年的数据点
  scale_color_manual(labels = ("Up", "Down"), values = ("#A6D854","#FC4E07")) +  
  xlim(.5, 2.5) )
# 添加文本信息
base_plot=( base_plot + geom_text(label=left_label, y=df['1970'], x=0.95,  size=10,ha='right')
+ geom_text(label=right_label, y=df['1979'], x=2.05, size=10,ha='left')
+ geom_text(label="1970", x=1, y=1.02*(np.max(np.max(df[['1970','1979']]))),  size=12)   
+ geom_text(label="1979", x=2, y=1.02*(np.max(np.max(df[['1970','1979']]))),  size=12) 
+theme_void()
+  theme(
    aspect_ratio =1.5,
    figure_size = (5, 6),
     dpi = 100
  )
)
print(base_plot)

#5-2坡度图 多年份对比
import pandas as pd
import numpy as np
from plotnine import *
df=pd.read_csv('Slopecharts_Data2.csv')

df['group']=df.apply(lambda x: "green" if x['2007']>x['2013'] else "red",axis=1)
df2=pd.melt(df, id_vars=["continent",'group'])
df2.value=df2.value.astype(int)
df2.variable=df2.variable.astype(int)
left_label =df2.apply(lambda x:  x['continent']+','+ str(x['value']) if x['variable']==2007 else "",axis=1)
right_label=df2.apply(lambda x:  x['continent']+','+ str(x['value']) if x['variable']==2013 else "",axis=1)
left_point=df2.apply(lambda x: x['value'] if x['variable']==2007 else np.nan,axis=1)
right_point=df2.apply(lambda x: x['value'] if x['variable']==2013 else np.nan,axis=1)

base_plot=( ggplot(df2) + 
  geom_line(aes(x='variable', y='value',group='continent', color='group'),size=.75) + 
  geom_vline(xintercept=2007, linetype="solid", size=.1) + 
  geom_vline(xintercept=2013, linetype="solid", size=.1) +
  geom_point(aes(x='variable', y=left_point), size=3,shape='o',fill="grey",color="red") + 
  geom_point(aes(x='variable', y=right_point), size=3,shape='o',fill="grey",color="red") + 
  scale_color_manual(labels = ("Up", "Down"), values = ("#FC4E07",  "#A6D854")) +  
  xlim(2001, 2018) )
base_plot=( base_plot + geom_text(label=left_label, y=df2['value'], x=2007,  size=9,ha='right')
+ geom_text(label=right_label, y=df2['value'], x=2013, size=9,ha='left')
+ geom_text(label="2007", x=2007, y=1.05*(np.max(df2.value)),  size=12)   
+ geom_text(label="2013", x=2013, y=1.05*(np.max(df2.value)),  size=12) 
+theme_void()
+  theme(
    aspect_ratio =1.2,
    figure_size = (7, 9),
     dpi = 100 ))
print(base_plot)

6、南丁格尔玫瑰图
#南丁格尔玫瑰图 多数据系列
import numpy as np
from matplotlib import cm,colors
from matplotlib import pyplot as plt
from matplotlib.pyplot import figure, show, rc
import pandas as pd
plt.rcParams["patch.force_edgecolor"] = True
plt.rc('axes',axisbelow=True)  
mydata=pd.DataFrame(dict(day=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],
                      Peter=[10, 60, 50, 20,10,90,30],
                      Jack=[20,50, 10, 10,30,60,50],
                      Eelin=[30, 50, 20, 40,10,40,50]))
mydata['sum']=mydata.iloc[:,1:4].apply(np.sum,axis=1)
mydata=mydata.sort_values(by='sum', ascending=False)#.iloc[:,0:3]
#df['City']=df['City'].astype("category",categories= df['City'],ordered=True)
n_row = mydata.shape[0]
n_col = mydata.shape[1]
angle = np.arange(0,2*np.pi,2*np.pi/n_row)
   radius1 = np.array(mydata.Peter)
radius2 = np.array(mydata.Jack)
radius3 = np.array(mydata.Eelin)
cmap=cm.get_cmap('Reds',n_col)
color=[colors.rgb2hex(cmap(i)[:3]) for i in range(cmap.N) ]
fig = figure(figsize=(4,4),dpi =90)    
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
ax.set_theta_offset(np.pi/2-np.pi/n_row)
#当set_theta_direction的参数值为-1或者是'clockwise'的时候,正方向为顺时针;
ax.set_theta_direction(-1)
#方法用于设置极径标签显示位置,参数为标签所要显示在的角度
ax.set_rlabel_position(360-180/n_row)
p1 = plt.bar(angle,radius1, color=color[0],edgecolor="k",width=0.90,alpha=0.9,label="Peter")
p2 = plt.bar(angle,radius2, color=color[1],edgecolor="k",width=0.90, bottom=radius1,alpha=0.9,label="Jack")
p3 = plt.bar(angle,radius3, color=color[2],edgecolor="k",width=0.90, bottom=radius1+radius2,alpha=0.9,label="Eelin")
#p4 = plt.bar(ind, without, width, color="grey", bottom=deficient)
#plt.bar(angle,radius, color='#F8766D',edgecolor="k",width=0.90)
plt.legend(loc="center",bbox_to_anchor=(1.25, 0, 0, 1))
plt.ylim(0,225)
plt.xticks(angle,labels=mydata.day,size=12)
plt.yticks(np.arange(0,201,50),verticalalignment='center',horizontalalignment='right')
plt.grid(which='major',axis ="x", linestyle='-', linewidth='0.5', color='gray',alpha=0.5)
plt.grid(which='major',axis ="y", linestyle='-', linewidth='0.5', color='gray',alpha=0.5)

#南丁格尔玫瑰图 单数据系列
import numpy as np
from matplotlib import cm,colors
from matplotlib import pyplot as plt
from matplotlib.pyplot import figure, show, rc
import pandas as pd
plt.rcParams["patch.force_edgecolor"] = True
plt.rc('axes',axisbelow=True)  
mydata=pd.DataFrame(dict(day=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],
                      Price=[50, 60, 70, 20,90,110,30]))
n_row= mydata.shape[0]
angle = np.arange(0,2*np.pi,2*np.pi/n_row)
radius = np.array(mydata.Price)
       
fig = figure(figsize=(4,4),dpi =90) 
#极坐标条形图,polar为True   
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
ax.set_theta_offset(np.pi/2-np.pi/n_row)
#当set_theta_direction的参数值为1,'counterclockwise'或者是'anticlockwise'的时候,正方向为逆时针;
#当set_theta_direction的参数值为-1或者是'clockwise'的时候,正方向为顺时针;
ax.set_theta_direction(-1)
#方法用于设置极径标签显示位置,参数为标签所要显示在的角度
ax.set_rlabel_position(360-180/n_row)

#plt.bar(angle,radius, color='#70A6FF',edgecolor="k",width=0.90,alpha=0.9)
plt.bar(angle,radius, color='#F9837A',edgecolor="k",width=0.90,alpha=0.9)
#x轴坐标轴标签
plt.xticks(angle,labels=mydata.day,size=12)
#plt.ylim(-15,125)     
plt.ylim(0,125)   
plt.yticks(np.arange(0,120,20),verticalalignment='center',horizontalalignment='right')
 
plt.grid(which='major',axis ="x", linestyle='-', linewidth='0.5', color='gray',alpha=0.5)
plt.grid(which='major',axis ="y", linestyle='-', linewidth='0.5', color='gray',alpha=0.5)
plt.show()
#fig.savefig('极坐标图2.pdf')
7、径向柱图、极坐标跨度图。
#7-1 径向图 单数据系列
import datetime
import numpy as np
from matplotlib import cm,colors
from matplotlib import pyplot as plt
from matplotlib.pyplot import figure, show, rc
import pandas as pd
plt.rcParams["patch.force_edgecolor"] = True
#plt.rc('axes',axisbelow=True)
plt.rcParams['axes.axisbelow'] = True

def dateRange(beginDate, endDate):
    dates = []
    dt = datetime.datetime.strptime(beginDate, "%Y-%m-%d")
    date = beginDate[:]
    while date <= endDate:
        dates.append(date)
        dt = dt + datetime.timedelta(1)
        date = dt.strftime("%Y-%m-%d")
    return dates

mydata=pd.DataFrame(dict(day=dateRange("2016-01-01", "2016-02-01"),
                      Price=-np.sort(-np.random.normal(loc=30,scale=10,size=32))+
                             np.random.normal(loc=3,scale=3,size=32)))

mydata['day']=pd.to_datetime(mydata['day'], format="%Y/%m/%d")
n_row=mydata.shape[0]
angle = np.arange(0,2*np.pi,2*np.pi/n_row)
radius = np.array(mydata.Price)

fig = figure(figsize=(4,4),dpi =90)    
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
ax.set_theta_offset(np.pi/2-np.pi/n_row)
#当set_theta_direction的参数值为1,'counterclockwise'或者是'anticlockwise'的时候,正方向为逆时针;
#当set_theta_direction的参数值为-1或者是'clockwise'的时候,正方向为顺时针;
ax.set_theta_direction(-1)
ax.set_rlabel_position(360-180/n_row)
cmap=cm.get_cmap('Blues_r',n_row)
color=[colors.rgb2hex(cmap(i)[:3]) for i in range(cmap.N) ]

plt.bar(angle,radius,color=color,alpha=0.9,width=0.2,align="center", linewidth=0.25)

plt.ylim(-15,60)
index=np.arange(0,n_row,3)
plt.xticks(angle[index],labels=[x.strftime('%m-%d') for x in mydata.day[index]],size=12)
plt.yticks(np.arange(0,60,10),verticalalignment='center',horizontalalignment='right')

plt.grid(which='major',axis ="x", linestyle='-', linewidth='0.5', color='gray',alpha=0.5)
plt.grid(which='major',axis ="y", linestyle='-', linewidth='0.5', color='gray',alpha=0.5)

#7-2 径向图 多数据系列
import numpy as np
from matplotlib import cm,colors
from matplotlib import pyplot as plt
from matplotlib.pyplot import figure, show, rc
import pandas as pd
plt.rcParams["patch.force_edgecolor"] = True
mydata=pd.DataFrame(dict(day=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],
                      Peter=[10, 60, 50, 20,10,90,30],
                      Jack=[20,50, 10, 10,30,60,50],
                      Eelin=[30, 50, 20, 40,10,40,50]))
n_row = mydata.shape[0]
n_col= mydata.shape[1]
angle = np.arange(0,2*np.pi,2*np.pi/n_row) 
cmap=cm.get_cmap('Reds',n_col)
color=[colors.rgb2hex(cmap(i)[:3]) for i in range(cmap.N) ]
radius1 = np.array(mydata.Peter)
radius2 = np.array(mydata.Jack)
radius3 = np.array(mydata.Eelin)
fig = figure(figsize=(4,4),dpi =90)    
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
ax.set_theta_offset(np.pi/2)
ax.set_theta_direction(-1)
ax.set_rlabel_position(360)

barwidth1=0.2  
barwidth2=0.2
plt.bar(angle,radius1,width=barwidth2, align="center",color=color[0],edgecolor="k",alpha=1,label="Peter")
plt.bar(angle+barwidth1,radius2,width=barwidth2,align="center", color=color[1],edgecolor="k",alpha=1,label="Jack")
plt.bar(angle+barwidth1*2,radius3,width=barwidth2,align="center", color=color[2],edgecolor="k",alpha=1,label="Eelin")
plt.legend(loc="center",bbox_to_anchor=(1.2, 0, 0, 1))
plt.ylim(-30,100)
plt.xticks(angle+2*np.pi/n_row/4,labels=mydata.day,size=12)
plt.yticks(np.arange(0,101,30),verticalalignment='center',horizontalalignment='right')
plt.grid(which='major',axis ="x", linestyle='-', linewidth='0.5', color='gray',alpha=0.5)
plt.grid(which='major',axis ="y", linestyle='-', linewidth='0.5', color='gray',alpha=0.5)

#7-3 极坐标跨度图
import numpy as np
from matplotlib import cm#,colors
from matplotlib import pyplot as plt
from matplotlib.pyplot import figure, show, rc
import pandas as pd
import matplotlib as mpl

plt.rcParams["patch.force_edgecolor"] = True
df=pd.read_csv('PloarRange_Data.csv')
fig = figure(figsize=(5,5),dpi =90)    
ax = fig.add_axes([0.1, 0.1, 0.6, 0.6], polar=True)

ax.set_theta_offset(np.pi / 2)
ax.set_theta_direction(-1)
ax.set_rlabel_position(0)

plt.xticks(np.arange(0,359,30)/180*np.pi,["%.2d" % i for i in np.arange(1,13,1)], color="black", size=12)
plt.ylim(-10,35)
plt.yticks(np.arange(-10,40,10),color="black", size=12,verticalalignment='center',horizontalalignment='right')
plt.grid(which='major',axis ="x", linestyle='-', linewidth='0.5', color='gray',alpha=0.5)
plt.grid(which='major',axis ="y", linestyle='-', linewidth='0.5', color='gray',alpha=0.5)
N = df.shape[0]
x_angles = [n / float(N) * 2 * np.pi for n in range(N)]
upperlimits =(df['max.temperaturec']-df['min.temperaturec']).values
lowerlimits = df['min.temperaturec'].values

colors = cm.Spectral_r(upperlimits / float(max(upperlimits)))

ax.bar(x_angles,lowerlimits, color='none',edgecolor='none',width=0.01,alpha=1)
ax.bar(x_angles,upperlimits, color=colors,edgecolor='none',width=0.02, bottom=lowerlimits,alpha=1)

ax2 = fig.add_axes([0.8, 0.25, 0.05, 0.3])
cmap = mpl.cm.Spectral_r
norm = mpl.colors.Normalize(vmin=0, vmax=20)
bounds = np.arange(0,20,0.1)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap=cmap,norm=norm,boundaries=bounds,ticks=np.arange(0,20,5),spacing='proportional',label='Temperature')

plt.show()

8、雷达图。
#8-1 雷达图
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from math import pi
from matplotlib.pyplot import figure, show, rc 
plt.rcParams["patch.force_edgecolor"] = True
df = pd.DataFrame(dict(categories=['var1', 'var2', 'var3', 'var4', 'var5'], group_A=[38.0, 29, 8, 7, 28], group_B=[1.5, 10, 39, 31, 15]))
N = df.shape[0]
angles = [n / float(N) * 2 * pi for n in range(N)]
angles += angles[:1]

fig = figure(figsize=(4,4),dpi =90)  
ax = fig.add_axes([0.1, 0.1, 0.6, 0.6], polar=True)
ax.set_theta_offset(pi / 2)
ax.set_theta_direction(-1)
ax.set_rlabel_position(0)
plt.xticks(angles[:-1], df['categories'], color="black", size=12)
plt.ylim(0,45)
plt.yticks(np.arange(10,50,10),color="black", size=12,verticalalignment='center',horizontalalignment='right')
plt.grid(which='major',axis ="x", linestyle='-', linewidth='0.5', color='gray',alpha=0.5)
plt.grid(which='major',axis ="y", linestyle='-', linewidth='0.5', color='gray',alpha=0.5)

values=df['group_A'].values.flatten().tolist()
values += values[:1]
ax.fill(angles, values, '#7FBC41', alpha=0.3)
ax.plot(angles, values, marker='o', markerfacecolor='#7FBC41', markersize=8, color='k', linewidth=0.25,label="group A")

values=df['group_B'].values.flatten().tolist()
values += values[:1]
ax.fill(angles, values, '#C51B7D', alpha=0.3)
ax.plot(angles, values, marker='o', markerfacecolor='#C51B7D', markersize=8, color='k', linewidth=0.25,label="group B")
plt.legend(loc="center",bbox_to_anchor=(1.25, 0, 0, 1))

9、词云图。
#9-1 词云图
import chardet
import jieba
import numpy as np
from PIL import Image
import os
from os import path
from wordcloud import WordCloud,STOPWORDS,ImageColorGenerator
from matplotlib import pyplot as plt
from matplotlib.pyplot import figure, show, rc 
d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()
text = open(path.join(d,'WordCloud.txt')).read()
# 生成词云
#wc = WordCloud(scale=2,max_font_size = 100)
wc=WordCloud(font_path=None,  # 字体路径,英文不用设置路径,中文需要,否则无法正确显示图形
    width=400, # 默认宽度
    height=400, # 默认高度
    margin=2, # 边缘
    ranks_only=None, 
    prefer_horizontal=0.9, 
    mask=None, # 背景图形,如果想根据图片绘制,则需要设置
    scale=2, 
   color_func=None, 
   max_words=100, # 最多显示的词汇量
   min_font_size=4, # 最小字号
   stopwords=None, # 停止词设置,修正词云图时需要设置
   random_state=None, 
   background_color='white', 
   max_font_size=None, # 最大字号
   font_step=1, 
   mode='RGB', 
   relative_scaling='auto', 
   regexp=None, 
   collocations=True, 
   colormap='Reds', # matplotlib 色图,可更改名称进而更改整体风格
   normalize_plurals=True, 
   contour_width=0, 
   contour_color='black', 
   repeat=False)
wc.generate_from_text(text)
fig = figure(figsize=(4,4),dpi =100)  
plt.imshow(wc,interpolation='bilinear')
plt.axis('off')
plt.tight_layout()
plt.show()

出现的问题及解决方法

1.TypeError: Module ‘plotnine’ is not defined 解决方法:conda install plotnine 安装
2.astype() has no attrbute named ‘categories’ 解决方法:将categories属性删除,在新版本的pandas中已被弃用
完整代码请关注博主后联系获取
欢迎大家加我微信交流讨论(请备注csdn上添加)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/926146.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号