# pyecharts 的使用
pyecharts 官网 (opens new window) pyecharts 的画廊 (opens new window)
pip install pyecharts
# 折线图
# 导包,导入Line功能构建折线图对象
from pyecharts.charts import Line
from pyecharts.options import LabelOpts
# 得到折线图对象
line = Line()
# 添加x轴数据
1ine.add_xaxis(["中国", "美国", "英国"], label_opts=LabelOpts(is_show=False))
# 添加y轴数据
line.add_yaxis("GDp", [30, 20, 10])
# 生成图表
# render 会生成本地 HTML 文件,默认会在当前目录生成 render.html 文件
# 也可以传入路径参数,如 bar.render("mycharts.html")
1ine.render()
- 全局配置选项
from pyecharts.options import TitleOpts, LegendOpts, ToolboxOpts, VisualMapOpts, TooltipOpts
line.set_global_opts(
# 标题配置项
title_opts = TitleOpts(title = "测试", pos_left = "center", pos_bottom = "1%"),
# 图例配置项
legend_opts = LegendOpts(is_show = True),
# 工具箱配置项
toolbox_opts = ToolboxOpts(is_show = True)
# 视觉映射配置项
visualmap_opts = VisualMapOpts(is_show = True)
# 提示框配置项
tooltip_opts = TooltipOpts(is_show = True)
)
- 生成图片
# 导包
from pyecharts.render import make_snapshot
from snapshot_selenium import snapshot
# 生成图片
make_snapshot(snapshot, 1ine.render(), '00.png')
# 基础柱状图
from pyecharts.charts import Bar
from pyecharts.options import *
# 构建柱状图对象
bar = Bar()
# 添加x轴数据
bar.add_xaxis(["中国","美国","英国"])
# 添加y轴数据,并且不显示标签
bar.add_yaxis("GDP",[30,20,10], label_opts=LabelOpts(is_show=False))
# 反转x和y轴
bar.reversal_axis()
# 绘图
bar.render("基础柱状图.html")
- 添加时间线
from pyecharts.charts import Bar, Timeline
from pyecharts.options import *
bar1= Bar()
bar1.add_xaxis(["中围","美国","英国"])
bar1.add_yaxis("GDP",[30,20,10],label_opts=LabelOpts(position="right"))
bar2 = Bar()
bar2.add_xaxis(["中国","美国","英国"])
bar2.add_yaxis("GDp",[50,30,20],label_opts=LabelOpts(position="right"))
# 创建时间对象
# timeline = Timeline()
timeline = Timeline({
# 设置主题色
"theme": ThemeType.LIGHT # 默认 LIGHT
})
# timeline对象添加bar柱状图
timeline.add(bar1,"2021年GDP")
timeline.add(bar2,"2022年GDP")
# 设置时间线自动播放
timeline.add_schema(
play_interval=1000, # 自动播放的时间问隔,单位毫秒
is_timeline_show=True, # 是否任自动播放的时候,显示时间线
is_auto_play=True, # 是否自动播放
is_loop_play=True # 是否循环播放
)
# 通过时间线绘图
timeline.render("基础桂状图-时间线.html")
# 基础地图
from pyecharts.charts import Map
from pyecharts.options import VisualMapOpts
map = Map()
data = [
("北京市",99),
("台湾省",199),
("上海市",199),
("湖南省",299),
("安徽省",299),
("广州省",399),
("湖北省",599),
]
# maptype:具体参考 pyecharts.datasets.map_filenames.json
map.add("地图", data, "china")
# 设置全局配置
map.set_global_opts(
visualmap_opts=VisualMapOpts(
is_show=True,
is_piecewise=True, # 允许手动校准范围
pieces=[
{"min": 1, "max": 9, "label": "1-9", "color": '#FF0000'},
{"min": 10, "max": 99, "label": "10-99", "color": '#00FF00'},
{"min": 100, "max": 999, "label": "100-999", "color": '#0000FF'}
]
)
)
map.render()
# matplotlib 的使用
Matplotlib(matrix+plot+library的缩写)是一个Python 2D绘图库,与numpy、pandas共享数据科学三剑客的美誉,也是很多高级可视化库的基础
# plot函数语法及参数说明
# x: x轴数据
# y: y轴数据
# linewidth: 线条宽度
# linestyle: 指定折线的类型,可以是实线、虚线、点虚线、点点线等,默认文实线
# color: 线条颜色
# marker: 可以为折线图添加点,该参数是设置点的形状,还有很多样式,如圆形、三角形、正方形等;
# markersize: 标记点大小
# markerfacecolor: 标记点颜色
# markeredgecolor: 标记点边缘颜色
# markeredgewidth: 标记点边缘宽度
# markerfacecoloralt: 标记点填充颜色
# fillstyle: 标记点填充样式
# label: 图例标签
# alpha: 透明度
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
plt.plot(x, y)
plt.plot(x, y, color='red', marker='o', linestyle='-', linewidth=2, markersize=12)
plt.show()
# arcpy 的使用
# ArcToolbox 四至范围计算
import arcpy
import logging
logging.basicConfig(filename='log.txt', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
input_feature_class = arcpy.GetParameterAsText(0)
logging.info(input_feature_class)
field_name_1 = 'xmin'
field_name_2 = 'xmax'
field_name_3 = 'ymin'
field_name_4 = 'ymax'
try:
if not any(field.name == field_name_1 for field in arcpy.ListFields(input_feature_class)):
arcpy.AddField_management(input_feature_class, field_name_1, 'TEXT', field_length = 280)
if not any(field.name == field_name_2 for field in arcpy.ListFields(input_feature_class)):
arcpy.AddField_management(input_feature_class, field_name_2, 'TEXT', field_length = 280)
if not any(field.name == field_name_3 for field in arcpy.ListFields(input_feature_class)):
arcpy.AddField_management(input_feature_class, field_name_3, 'TEXT', field_length = 280)
if not any(field.name == field_name_4 for field in arcpy.ListFields(input_feature_class)):
arcpy.AddField_management(input_feature_class, field_name_4, 'TEXT', field_length = 280)
with arcpy.da.UpdateCursor(input_feature_class, ['SHAPE@',field_name_1,field_name_2,field_name_3,field_name_4]) as cursor:
for row in cursor:
geometry = row[0]
extent = geometry.extent
row[1] = extent.XMin
row[2] = extent.XMax
row[3] = extent.YMin
row[4] = extent.YMax
cursor.updateRow(row)
logging.info(str(extent.XMin))
arcpy.AddMessage("操作成功")
except Exception as e:
logging.error("操作失败 {}".format(e))
arcpy.AddError("操作失败 {}".format(e))
注意
不要加中文注释!!!
# 将84坐标系转为高德坐标系
# coding=utf-8
import arcpy
import math
def transformLat(x, y):
ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * math.sqrt(abs(x))
ret += (20.0 * math.sin(6.0 * x * math.pi) + 20.0 * math.sin(2.0 * x * math.pi)) * 2.0 / 3.0
ret += (20.0 * math.sin(y * math.pi) + 40.0 * math.sin(y / 3.0 * math.pi)) * 2.0 / 3.0
ret += (160.0 * math.sin(y / 12.0 * math.pi) + 320 * math.sin(y * math.pi / 30.0)) * 2.0 / 3.0
return ret
def transformLon(x, y):
ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * math.sqrt(abs(x))
ret += (20.0 * math.sin(6.0 * x * math.pi) + 20.0 * math.sin(2.0 * x * math.pi)) * 2.0 / 3.0
ret += (20.0 * math.sin(x * math.pi) + 40.0 * math.sin(x / 3.0 * math.pi)) * 2.0 / 3.0
ret += (150.0 * math.sin(x / 12.0 * math.pi) + 300.0 * math.sin(x / 30.0 * math.pi)) * 2.0 / 3.0
return ret
def delta(lat, lon):
a = 6378245.0 # 克拉索夫斯基椭球参数长半轴a
ee = 0.00669342162296594323 # 克拉索夫斯基椭球参数第一偏心率平方
dLat = transformLat(lon - 105.0, lat - 35.0)
dLon = transformLon(lon - 105.0, lat - 35.0)
radLat = lat / 180.0 * math.pi
magic = math.sin(radLat)
magic = 1 - ee * magic * magic
sqrtMagic = math.sqrt(magic)
dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * math.pi)
dLon = (dLon * 180.0) / (a / sqrtMagic * math.cos(radLat) * math.pi)
mgLat = lat + dLat
mgLon = lon + dLon
return mgLat, mgLon
def wgs84_to_gcj02(lat, lon):
if not (72.004 <= lon <= 137.8347 and 0.8293 <= lat <= 55.8271):
return lat, lon
dLat, dLon = delta(lat, lon)
return dLat, dLon
def convert_shp_to_gcj02(input_shp, output_shp):
reference = arcpy.SpatialReference(4490) #GCJ02和CGC2000的投影坐标系代码一样
with arcpy.da.UpdateCursor(input_shp, ['Shape@','FID']) as cursor:
for row in cursor:
shape = row[0]
new_points = []
if shape.type == "point":
lat = round(shape.firstPoint.Y, 20)
lon = round(shape.firstPoint.X, 15)
new_lat, new_lon = wgs84_to_gcj02(lat, lon)
new_point = arcpy.Point(new_lon, new_lat)
new_points.append(new_point)
elif shape.type in ["polyline", "polygon"]:
for part in shape:
part_points = []
for point in part:
if point:
lat = round(point.Y, 15)
lon = round(point.X, 15)
new_lat, new_lon = wgs84_to_gcj02(lat, lon)
new_point = arcpy.Point(new_lon, new_lat)
part_points.append(new_point)
new_points.append(part_points)
if shape.type == "point":
new_shape = arcpy.PointGeometry(new_points[0])
elif shape.type == "polyline":
new_shape = arcpy.Polyline(arcpy.Array(new_points))
elif shape.type == "polygon":
array = arcpy.Array(new_points)
# 一定要添加正确的空间参考 reference
new_shape = arcpy.Polygon(array,reference)
row[0] = new_shape
cursor.updateRow(row)
# 示例调用
input_shp = r"F:\DATA\菏泽\区县乡村\caoxian1\caoxian.shp"
convert_shp_to_gcj02(input_shp)
注意
arcpy.Polygon(array, reference) 一定要添加正确的空间参考 reference,否则会有 xy 容差
# 数据库的使用
# MySQL 数据库
在Python中,使用第三方库 pymysql 来完成对 MySQL 数据库的操作
pip install pymysql
创建到MySOL的数据库链接
from pymysql import Connection
# 获取到MySQL数据库的链接对象
conn = Connection(
host = 'localhost',
port = 3306,
user = 'root',
password = '123456',
db='cloud-user',
)
# 打印MySQL数据库软件信息
print(conn.get_server_info())
# 关闭到数据库的链接
conn.close()
- 执行SQL语句
from pymysql import Connection
# 获取到MySQL数据库的链接对象
conn = Connection(
host = 'localhost',
port = 3306,
user = 'root',
password = '123456',
db='cloud-user',
)
# 执行DML语句
cursor = conn.cursor()
cursor = conn.cursor()
conn.select_db("cloud-user")
cursor.execute("CREATE TABLE student(id INT, name VARCHAR(255))")
cursor.execute("insert into student values(10001,'sylone')")
conn.commit() # 上面的语句需要 commit() 方法
# 如果不想手动 commit 确认,可以在构建链接对象的时候,设置自动commit的属性
# autocommit=True
# 执行DQL语句
cursor = conn.cursor()
sql = 'select * from tb_user'
cursor.execute(sql)
result = cursor.fetchall()
for i in result:
print(i)
# 关闭到数据库的链接
conn.close()