1.#画2D折线图
#引用matplotlib
import matplotlib.pyplot as plt
#plt.plot(x,y)
plt.plot([1,2,3,4,5,6,7,8,9],[4,5,3,6,7,8,9,6,8])
plt.show()
效果图:
2D折线图.png
import matplotlib.pyplot as plt
x = [1,2,3,4,5,6,7,8,9,10,11,12]
y = [6,3,6,3,7,1,2,3,5,6,4,8]
#x轴标签
plt.xlabel('Month')
#y轴标签
plt.ylabel('Sales')
#图表标题
plt.title('Sales of Company\nCompany A and Company B')
plt.plot(x,y)
plt.show()
2D折线图.png
多数据情况下,legend()的作用:给图像加上图例
import matplotlib.pyplot as plt
#数据组1
x = [1,2,3,4,5,6,7,8,9,10,11,12]
y = [6,3,6,3,7,1,2,3,5,6,4,8]
#数据组2
x2 = [1,2,3,4,5,6,7,8,9,10,11,12]
y2 = [6,5,8,6,7,8,4,3,5,9,4,8]
#x,y轴标题
plt.xlabel('Month')
plt.ylabel('Sales')
#图表标题
plt.title('Sales of Company\nCompany A and Company B')
plt.plot(x,y,label='Company A')
plt.plot(x2,y2,label='Company B')
#给图像加上图例
plt.legend()
plt.show()
数据组折线图.png
柱状图绘制
1组数据:
import matplotlib.pyplot as plt
x = ['Company A','Company B','CompanyC']
y = [1,2,3]
plt.bar(x,y,label='Bar_1')
plt.xlabel('Company\'s Name')
plt.ylabel('2018 Sales')
plt.title('ABC Compare')
plt.show()
1组数据柱状图.png
2组数据
import matplotlib.pyplot as plt
#奇数月
x = [1,3,5]
y = [3,2,4]
#偶数月
x2 = [2,4,6]
y2 = [2,4,1]
plt.xlabel('Month')
plt.ylabel('Sales')
#可设置柱状的颜色
plt.bar(x,y,label='A',color='pink')
plt.bar(x2,y2,label='B')
plt.legend()
plt.title('Company\'s Sales')
plt.show()
image.png
直方图绘制
import matplotlib.pyplot as plt
age = [1,2,3,4,7,8,9,5,10,13,14,18,8,23,21,25,26,29,24,30,36,34,37,40,47,46,43,48,
53,58,56,54,73,75,70,60,62,67,77,80,85,82,90,100]
#分类规则
bins = [0,10,20,30,40,50,60,70,80,90,100]
plt.hist(age,bins,histtype='bar',rwidth=0.8)
plt.xlabel('Age')
plt.ylabel('Num')
plt.title('The City A Age Hist')
plt.show()
image.png
散点图绘制
import matplotlib.pyplot as plt
x = [1,2,3,4,5,6,7,8,9,10]
y = [1,2,1.5,3,5.4,6.3,7.2,7.9,8.7,10]
#marker:点的形状
#s:点的大小
plt.scatter(x,y,label='scatter_plot',marker='*',s=100)
plt.xlabel('x')
plt.ylabel('y')
plt.title('A scatter plot')
plt.legend()
plt.show()
image.png
堆栈图
import matplotlib.pyplot as plt
month = [1,2,3,4,5,6,7,8,9,10,11,12]
A = [1,2,3,4,5,6,7,8,9,20,11,12]
B = [10,20,30,40,50,60,70,80,90,100,110,120]
C = [200,190,180,170,160,150,140,130,120,110,100,90]
D = [50,40,50,60,53,56,57,58,60,59,62,55]
plt.plot([],[],color='m',label='Company A',linewidth=5)
plt.plot([],[],color='c',label='Company B',linewidth=5)
plt.plot([],[],color='r',label='Company C',linewidth=5)
plt.plot([],[],color='k',label='Company D',linewidth=5)
plt.stackplot(month,A,B,C,D,colors=['m','c','r','k'])
plt.xlabel('month')
plt.ylabel('sales')
plt.title('A B C D sales')
plt.legend()
plt.show()
堆栈图_1.png
饼状图
import matplotlib.pyplot as plt
sales = [1.9,2,3.5,6]
company_name = ['Company A','Company B','Company C','Company D']
colors_1= ['azure','lavender','pink','gray']
plt.pie(sales,
labels = company_name,
colors=colors_1,
startangle=90,
shadow=True,
autopct = '%1.1f%%' #让系统自动算出半分比,并显示在饼状图上
explode=(0.1,0,0,0)) #分离出某块饼,0.1的位置对应的模块分离
plt.show()
饼状图
网友评论