数据可视化代码总结
要下的库:
pip install matplotlib
pip install numpy
pip install pyecharts==0.5.11
pip install echarts-countries-pypkg
pip install echarts-china-provinces-pypkg
pip install echarts-china-cities-pypkg
matplotlib
用matplotlib和numpy画个饼图
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei'] #设置字体
plt.title("饼图");#设置标题
labels = '计算机系','机械系','管理系','社科系'
sizes = [45,30,15,10] #设置每部分大小
explode = (0,0.0,0.1,0) #设置每部分凹凸
counterclock = False#设置顺时针方向
plt.pie(sizes,explode=explode,labels=labels,autopct='%1.1f%%',shadow=True,startangle=90) #设置饼图的起始位置,startangle=90表示开始角度为90度
plt.show()
#绘制散点图
import matplotlib.pyplot as plt
import numpy as np
x = np.random.rand(100)
y = np.random.rand(100)
plt.scatter(x,y,color='green')
plt.show()
#柱状图
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font_set = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=15)#导入宋体字体文件
x = [0,1,2,3,4,5]
y = [1,2,3,2,4,3]
plt.bar(x,y)#竖的条形图
plt.title("柱状图",FontProperties=font_set); #图标题
plt.xlabel("x轴",FontProperties=font_set);
plt.ylabel("y轴",FontProperties=font_set);
plt.show()
#极坐标图
import matplotlib.pyplot as plt
import numpy as np
theta=np.arange(0,2*np.pi,0.02)
ax1 = plt.subplot(121, projection='polar')
ax1.plot(theta,theta/6,'--',lw=2)
plt.show()
#随机生成柱状图
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import numpy as np
font_set = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=15)#导入宋体字体文件
x = np.arange(10)
y = np.random.randint(0,20,10)
plt.bar(x, y)
plt.show()
#生成直方图
import matplotlib.pyplot as plt
import numpy as np
mean, sigma = 0, 1
x = mean + sigma*np.random.randn(10000)
plt.hist(x,50,histtype='bar',facecolor='blue',alpha=0.80)#normed=1
plt.show()
#绘制直线
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font_set = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=20)#导入宋体字体文件
dataX = [1,2,3,4]
dataY = [2,4,4,2]
plt.plot(dataX,dataY)
plt.title("绘制直线",FontProperties=font_set);
plt.xlabel("x轴",FontProperties=font_set);
plt.ylabel("y轴",FontProperties=font_set);
plt.show()
#绘制两条折线
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10) # 取值依次为0-9的等差数列
y = np.sin(x)
z = np.cos(x)
plt.plot(x, y, marker="*", linewidth=3, linestyle="--", color="red")#marker设置数据点样式,linewidth设置线宽,linestyle设置线型样式,color设置颜色
plt.plot(x, z)
plt.title("matplotlib")
plt.xlabel("x")
plt.ylabel("y")
plt.legend(["Y","Z"], loc="upper right")# 设置图例
plt.grid(True)
plt.show()
#用subplot划分区域内所有子图
import matplotlib.pyplot as plt
fig=plt.figure()
fig1=fig.add_subplot(3,3,1)
fig2=fig.add_subplot(3,3,2)
fig3=fig.add_subplot(3,3,3)
fig4=fig.add_subplot(3,3,4)
fig5=fig.add_subplot(3,3,5)
fig6=fig.add_subplot(3,3,6)
fig7=fig.add_subplot(3,3,7)
fig8=fig.add_subplot(3,3,8)
fig9=fig.add_subplot(3,3,9)
plt.show()
pyecharts
商家销售
#导入柱状图-Bar
from pyecharts import Bar
#设置行名
columns = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
#设置数据
data1 = [25, 24, 36, 10, 90, 100]
data2 = [35, 64, 16, 60, 100, 50]
#设置柱状图的主标题与副标题
bar = Bar("柱状图", "两个商家的销售量")
#添加柱状图的数据及配置项
bar.add("商家A",columns, data1, mark_line=["average"], mark_point=["max", "min"])
bar.add("商家B",columns, data2, mark_line=["average"], mark_point=["max", "min"])
#生成本地文件(默认为.html文件)
bar.render("商家销售量柱形图.html")
from pyecharts import Line
###设置行名
columns = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
###设置数据
data1 = [25, 24, 36, 10, 90, 100]
data2 = [35, 64, 16, 60, 100, 50]
line =Line("面积图", "两个商家的销售量")
line.add("商家A", columns, data1, is_filled = True, area_opacity = 0.5, is_label_show=True,is_smooth=True)
line.add("商家B", columns, data2, is_filled = True, area_opacity = 0.5, is_label_show=True)
##line.show_config()
line.render("商家销售量面积图.html")
from pyecharts import Grid
from pyecharts import Bar
from pyecharts import Line
#设置行名
columns = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
#设置数据
data1 = [25, 24, 36, 10, 90, 100]
data2 = [35, 64, 16, 60, 100, 50]
#设置柱状图的主标题与副标题
bar = Bar("柱状图", "两个商家的销售量")
#添加柱状图的数据及配置项
bar.add("商家A", columns, data1, mark_line=["average"], mark_point=["max", "min"])
bar.add("商家B", columns, data2, mark_line=["average"], mark_point=["max", "min"])
#设置折线图标题位置
line = Line("面积图","两个商家的销售量",title_top="45%")
line.add("商家A", columns, data1, is_filled = True, area_opacity = 0.5, is_label_show=True)
line.add("商家B", columns, data2, is_filled = True, area_opacity = 0.5, is_label_show=True)
grid = Grid()
#设置两个图表的相对位置
grid.add(bar, grid_bottom="60%")
grid.add(line, grid_top="60%")
grid.render("两个商家销售量双图.html")
from pyecharts import Overlap
from pyecharts import Bar
from pyecharts import Line
#设置行名
columns = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
#设置数据
data1 = [25, 24, 36, 10, 90, 100]
data2 = [35, 64, 16, 60, 100, 50]
overlap = Overlap()
bar = Bar("柱状图-折线图合并", "两个商家的销售量")
#添加柱状图的数据及配置项
bar.add("商家A", columns, data1)
bar.add("商家B", columns, data2)
line =Line()
line.add("商家A", columns, data1, is_label_show=True)
line.add("商家B", columns, data2, is_label_show=True)
overlap.add(bar)
overlap.add(line)
overlap.render("两个商家的销售量双图合并.html")
疫情图
import requests
import json
from pyecharts import Map, Geo
##r = requests.get("https://coronavirus-tracker-api.herokuapp.com/confirmed")
##with open('info_confirmed.txt','w') as f:
## f.write(r.text)
fq = open("info_confirmed.txt","r")
json_text = json.loads(fq.read())#读取文件
fq.close()
value = [] # 各省份的确诊人数
attr = [] # 省份名称
date = "12/20/20"
for i in range(0,len(json_text["locations"])):
if json_text["locations"][i]["country"] == "China":#判断中国数据
attr.append(json_text["locations"][i]["province"])
value.append(int(json_text["locations"][i]["history"][date]))
province_ref = { 'Sichuan':'四川',
'Zhejiang':'浙江',
'Fujian': '福建',
'Jiangsu':'江苏',
'Hunan': '湖南',
'Shandong':'山东',
'Anhui':'安徽',
'Guangdong':'广东',
'Hebei':'河北',
'Hubei':'湖北',
'Jilin':'吉林',
'Shanghai':'上海',
'Jiangxi':'江西',
'Guangxi':'广西',
'Guizhou':'贵州',
'Beijing':'北京',
'Yunnan':'云南',
'Chongqing':'重庆',
'Henan':'河南',
'Shaanxi':'陕西',
'Shanxi':'山西',
'Liaoning':'辽宁',
'Xinjiang':'新疆',
'Neimenggu':'内蒙古',
'Heilongjiang':'黑龙江',
'Tianjin':'天津',
'Gansu':'甘肃',
'Hainan': '海南',
'Qinghai':'青海',
'Ningxia':'宁夏',
'Hong Kong':'香港',
'Inner Mongolia':'内蒙古',
'Macau':'澳门',
'Tibet':'西藏',
'Unknown':'台湾'
}
attr0 = [province_ref[attr[i]] for i in range(len(attr))]
print(attr0)
print(value)
map0 = Map("中国地图示例", width=1200, height=600)
map0.add("中国新冠状病毒疫情地图", attr0,value, maptype="china",type='heatmap',is_visualmap=True,
visual_text_color='#000', visual_range=[min(value), max(value)], is_map_symbol_show=False,
label_text_size=0.5)
map0.render(path="中国疫情地图.html")
## https://zhuanlan.zhihu.com/p/122971494
## 获取全部数据:https://coronavirus-tracker-api.herokuapp.com/all
##
## 获取确诊数据:https://coronavirus-tracker-api.herokuapp.com/confirmed
##
## 获取死亡数据:https://coronavirus-tracker-api.herokuapp.com/deaths
##
## 获取治愈数据:https://coronavirus-tracker-api.herokuapp.com
##import requests
import json
from pyecharts import Map, Geo
##res=requests.get(url="https://coronavirus-tracker-api.herokuapp.com/confirmed")
##fq=open("info_confirmed.txt","w")
##fq.write(res.text)
fq=open("info_confirmed.txt","r")
json_text=json.loads(fq.read())#读取文件
fq.close()
date="12/20/20"
'''
location=json_text["locations"][0]["country"]
data=json_text["locations"][0]["history"]["3/12/20"]
print(str(data[0])+" "+location)
'''
value=[]
attr=[]
ussum=0
chinasum=0
for i in range(0,len(json_text["locations"])):
if json_text["locations"][i]["country"]=="US":#判断美国数据
ussum=ussum+int(json_text["locations"][i]["history"][date])
elif json_text["locations"][i]["country"]=="China":#判断中国数据
#attr.append(json_text["confirmed"]["locations"][i]["province"])
chinasum=chinasum+int(json_text["locations"][i]["history"][date])
#print("chinasum"+str(sum))
else:
attr.append(json_text["locations"][i]["country"])
value.append(json_text["locations"][i]["history"][date])
attr.append("China")
value.append(int(chinasum))
attr.append("United States")
value.append(int(ussum))
print(value)
print(attr)
map0 = Map("世界地图示例", width=1200, height=600)
map0.add("世界新冠状病毒疫情地图", attr,value, maptype="world",type='heatmap',is_visualmap=True,
visual_text_color='#000', visual_range=[min(value), max(value)], is_map_symbol_show=False,
label_text_size=0.5)
map0.render(path="世界新冠状病毒疫情地图老师的代码.html")
#,is_label_show=True, 展示国家名称
pyecharts绘图
from pyecharts import Pie
attr = ["衬衫", "羊毛衫", "运动裤", "皮鞋", "高跟鞋", "袜子"]
v1 = [31, 12, 13, 10, 15, 10]
pie = Pie("饼图")
pie.add("", attr, v1, is_label_show=True)
pie.render("饼图.html")
from pyecharts import Line
attr=["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
v1 =[25, 24, 36, 10, 90, 100]
v2=[35, 64, 16, 60, 100, 50]
line =Line("折线图")
line.add("商家A", attr, v1, is_fill = True,area_opacity=0.5)
line.add("商家B", attr, v2,is_fill = True,is_smooth=True,area_opacity=0.5)
line.show_config()
line.render("面积图.html")
from pyecharts import Line
attr=["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
v1 =[25, 24, 36, 10, 90, 100]
line =Line("折线图")
line.add("商家A", attr, v1, mark_point=["max"])
line.show_config()
line.render("折线图.html")
from pyecharts import Bar
v1 = [70,85,95,64]
v2 = [80,75,85,70]
str1 = ['数学','物理','化学','英语']
bar = Bar('柱状图','分数')
bar.add("小明", str1 , v1, is_stack=False)
bar.add("小红", str1 , v2, is_stack=False)
bar.render("柱状不堆叠.html")
#柱状图堆叠
from pyecharts import Bar
v1 = [70,85,95,64]
v2 = [80,75,85,70]
str1 = ['数学','物理','化学','英语']
bar = Bar('柱状图','分数')
bar.add("小明", str1 , v1, is_stack=True)
bar.add("小红", str1 , v2, is_stack=True)
bar.render("柱状不堆叠.html")
from pyecharts import Bar
v1 = [70,85,95,64]
str1 = ['数学','物理','化学','英语']
bar1 = Bar('柱状图','分数')
bar1.add('成绩',str1,v1,is_more_utils = True)
bar1.render("柱状图.html")