一、点线图
核心部分:
import matplotlib.pyplot as plt
#fig为整张图像,ax为曲线
fig, ax = plt.subplots(figsize = (16,12), dpi = 50)
#输入曲线参数,a1为x轴(可忽略),a2和a3为y轴,alpha为透明度
ax.plot(a1, a2, c = 'red', alpha = 0.5)
ax.plot(a1, a3, c = 'blue', alpha = 0.5)
#在两条线之间填充颜色
ax.fill_between(dates, highs, lows, facecolor = 'blue', alpha = 0.1)
#设置两条线共用的参数
ax.set_title("...", fontsize = 20)
ax.set_xlabel('', fontsize = 16)
ax.set_ylabel("...", fontsize = 16)
#X轴刻度标签字体斜体化
fig.autofmt_xdate()
#设置图的参数
ax.tick_params(axis = 'both', which = 'major', labelsize = 16)
#绘制图像
plt.show()
完整示例:
import csv
from datetime import datetime
import matplotlib.pyplot as plt
filename = 'data/death_valley_2018_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
#从文件中获取日期和最高温度
dates, highs, lows = [], [], []
for row in reader:
current_date = datetime.strptime(row[2], '%Y-%m-%d')
try:
high = int(row[4])
low = int(row[5])
except ValueError:
print(f"Missing data for {current_date}")
else:
dates.append(current_date)
highs.append(high)
lows.append(low)
#根据最高温度和最低温度绘制图形
fig, ax = plt.subplots(figsize = (16,12), dpi = 50)
ax.plot(dates, highs, c = 'red', alpha = 0.5)
ax.plot(dates, lows, c = 'blue', alpha = 0.5)
ax.fill_between(dates, highs, lows, facecolor = 'blue', alpha = 0.1)
#设置图形的格式
ax.set_title("2018年每日最高温度和最低温度\n美国加利福尼亚州死亡谷", fontsize = 20)
ax.set_xlabel('', fontsize = 16)
fig.autofmt_xdate()
ax.set_ylabel("温度 (F)", fontsize = 16)
ax.tick_params(axis = 'both', which = 'major', labelsize = 16)
plt.show()
二、散点图
方法1:只用plotly.express模块(可定制内容少,不推荐)
核心部分:
import plotly.express as px
fig = px.scatter(
#a,b均为列表
x = a,
y = b,
#两个坐标轴的名称
labels = {'x': '...', 'y': '...'},
#坐标轴范围
range_x = [-200, 200],
range_y = [-90, 90],
#图的大小
width = 800,
height = 800,
#图的标题
title = '...',
)
#产出html文件
fig.write_html('....html')
#绘制图像
fig.show()
完整示例:
import json
import plotly.express as px
filename = 'data/eq_data_1_day_m1.json'
with open(filename) as f:
all_eq_data = json.load(f)
all_eq_dicts = all_eq_data['features']
mags, titles, lons, lats = [],[],[],[]
for eq_dict in all_eq_dicts:
mag = eq_dict['properties']['mag']
title = eq_dict['properties']['title']
lon = eq_dict['geometry']['coordinates'][0]
lat = eq_dict['geometry']['coordinates'][1]
mags.append(mag)
titles.append(title)
lons.append(lon)
lats.append(lat)
fig = px.scatter(
x = lons,
y = lats,
labels = {'x': '经度', 'y': '纬度'},
range_x = [-200, 200],
range_y = [-90, 90],
width = 800,
height = 800,
title = '全球地震散点图',
)
fig.write_html('graph/global_earthquakes.html')
fig.show()
方法2:利用plotly.express + pandas 分析工具(推荐,可定制 + 图像中丰富的工具提示)
核心部分:
import plotly.express as px
import pandas as pd
import webbrowser
import os
data = pd.DataFrame(
#columns中为数据名称,顺序与zip()中的对应
data = zip(lons, lats, titles, mags), columns = ['...', '...', '...', '...']
)
data.head()
#散点图参数
fig = px.scatter(
data,
x = '...',
y = '...',
#两个坐标轴的名称
labels = {'x': '...', 'y': '...'},
#坐标轴范围
range_x = [-200, 200],
range_y = [-90, 90],
#图的大小
width = 800,
height = 800,
#图的标题
title = '...',
#每个点的大小
size = '...',
size_max = 10,
#每个点的颜色
color = '...',
#用的颜色渐变类型
color_continuous_scale = px.colors.sequential.Magma[::-1],
#每个点的详细信息的标题
hover_name = '...',
)
#产出html文件
fig.write_html('graph/global_earthquakes.html')
#在浏览器打开
edge_path = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
webbrowser.register('edge', None, webbrowser.BackgroundBrowser(edge_path))
html_file = os.path.abspath('graph/global_earthquakes.html')
url = f"file:///{html_file}"
webbrowser.get('edge').open(url)
import json
import plotly.express as px
import pandas as pd
import webbrowser
import os
filename = 'data/eq_data_1_day_m1.json'
with open(filename) as f:
all_eq_data = json.load(f)
all_eq_dicts = all_eq_data['features']
mags, titles, lons, lats = [],[],[],[]
for eq_dict in all_eq_dicts:
mag = eq_dict['properties']['mag']
title = eq_dict['properties']['title']
lon = eq_dict['geometry']['coordinates'][0]
lat = eq_dict['geometry']['coordinates'][1]
mags.append(mag)
titles.append(title)
lons.append(lon)
lats.append(lat)
data = pd.DataFrame(
data = zip(lons, lats, titles, mags), columns = ['经度', '纬度', '位置', '震级']
)
data.head()
fig = px.scatter(
# x = lons,
# y = lats,
data,
x = '经度',
y = '纬度',
labels = {'x': '经度', 'y': '纬度'},
range_x = [-200, 200],
range_y = [-90, 90],
width = 800,
height = 800,
title = '全球地震散点图',
size = '震级',
size_max = 10,
color = '震级',
color_continuous_scale = px.colors.sequential.Magma[::-1],
hover_name = '位置',
)
fig.write_html('graph/global_earthquakes.html')
edge_path = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
webbrowser.register('edge', None, webbrowser.BackgroundBrowser(edge_path))
html_file = os.path.abspath('graph/global_earthquakes.html')
url = f"file:///{html_file}"
webbrowser.get('edge').open(url)
注:这里最后用浏览器打开而不是fig.show()的原因参考这里
三、条形图
方法:利用offline模块
写法1:
核心部分:
from plotly.graph_objs import Bar, Layout
from plotly import offline
#将列表转化为条形图数据(a和b均为列表)
data = [Bar(x = a , y = b )]
x_axis_config = {'title': '...'}
y_axis_config ={'title': '...'}
#配置layout参数
my_layout = Layout(title = '...', xaxis = x_axis_config, yaxis = y_axis_config)
#在浏览器中生成图像
offline.plot({'data': data, 'layout': my_layout}, filename ='....html')
完整示例:
from die import Die
from plotly.graph_objs import Bar, Layout
from plotly import offline
die = Die()
results = []
for roll_num in range(10000):
result = die.roll()
results.append(result)
frequencies = []
for value in range(1, die.num_sides + 1):
frequency = results.count(value)
frequencies.append(frequency)
#对结果进行可视化
x_values = list(range(1, die.num_sides + 1))
data = [Bar(x = x_values, y = frequencies)]
x_axis_config = {'title': '结果'}
y_axis_config ={'title': '结果的频率'}
my_layout = Layout(title = '掷一个D6 1000次的结果', xaxis = x_axis_config, yaxis = y_axis_config)
offline.plot({'data': data, 'layout': my_layout}, filename ='graph/d6.html')
写法2:
核心部分:
from plotly import offline
#用字典来配置参数
data = [{
#设置类型为条形
'type': 'bar',
#这里a,b,c均为列表
'x': a,
'y': b,
#当鼠标指向条形的时候显示的信息
'hovertext' : c,
#条形参数
'marker': {
#颜色
'color': 'rgb(60, 100, 150)',
#轮廓线
'line': {'width': 1.5, 'color': 'rgb(25, 25, 25)'}
},
#条形不透明度
'opacity': 0.6,
}]
my_layout = {
#图的标题
'title':{
'text': '...',
'font': {'size': 28},
},
'xaxis': {
#坐标轴名称参数
'title': {
'text' : '...',
'font': {'size': 24}
},
#坐标轴刻度标签字号
'tickfont': {'size': 14},
},
'yaxis': {
'title': {
'text' : '...',
'font': {'size': 24}
},
'tickfont': {'size': 14},
},
}
#配置图像数据
fig = {'data': data, 'layout': my_layout}
#在浏览器中绘制图像
offline.plot(fig, filename = '....html')
完整示例:
import requests
from plotly.graph_objs import Bar
from plotly import offline
#执行API调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
headers = {'Accept': 'application/vnd.github.v3+json'}
r = requests.get(url, headers = headers)
print(f"Status code: {r.status_code}")
#处理结果
response_dict = r.json()
repo_dicts = response_dict['items']
repo_links, stars, labels = [], [], []
for repo_dict in repo_dicts:
repo_name = repo_dict['name']
repo_url = repo_dict['html_url']
repo_link = f"<a href = '{repo_url}'>{repo_name}</a>"
repo_links.append(repo_link)
stars.append(repo_dict['stargazers_count'])
owner = repo_dict['owner']['login']
description = repo_dict['description']
label = f"{owner}<br />{description}"
labels.append(label)
#可视化
data = [{
'type': 'bar',
'x': repo_links,
'y': stars,
'hovertext' : labels,
'marker': {
'color': 'rgb(60, 100, 150)',
'line': {'width': 1.5, 'color': 'rgb(25, 25, 25)'}
},
'opacity': 0.6,
}]
my_layout = {
'title':{
'text': 'GitHub上最受欢迎的Python项目',
'font': {'size': 28},
},
'xaxis': {
'title': {
'text' : 'Repository',
'font': {'size': 24}
},
'tickfont': {'size': 14},
},
'yaxis': {
'title': {
'text' : 'Repository',
'font': {'size': 24}
},
'tickfont': {'size': 14},
},
}
fig = {'data': data, 'layout': my_layout}
offline.plot(fig, filename = 'graph/python_repos.html')