1 引言
2 R code
3 Python code
4 结语
1 引言
尝试学习在 Quarto 文档里使用 Python,以查看全球的发电站分布。记录之。
2 R code
如果在 Quarto 中使用 Python 可以手动指定 Python 文件夹的位置。这里是 R
代码。
library(reticulate)
# Select the version of Python to be used
where_py <- "/Library/Frameworks/Python.framework/Versions/3.12/bin/python3"
use_python(where_py)
3 Python code
以下是 Python
代码。
3.1 加载库
import time
import numpy as np
import pandas as pd
import geopandas as gpd
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
from matplotlib import colormaps
from matplotlib.animation import FuncAnimation, PillowWriter
3.2 导入数据
数据来自 World Resources Institute,链接见脚注1。
3.3 数据清理
只选择四种 Hydro
、Coal
、Oil
、Wind
电力来源。
# Read data from CSV file
raw = pd.read_csv("global_power_plant_database_v1.3.0.csv")
<string>:2: DtypeWarning: Columns (10) have mixed types. Specify dtype option on import or set low_memory=False.
# Filter data based on the primary_fuel column
df = raw[raw["primary_fuel"].isin(["Hydro", "Coal", "Oil", "Wind"])]
3.4 看看配色
# Display a sample of colormaps
fig, ax = plt.subplots(figsize=(8, 2), dpi=300)
plt.imshow(
np.linspace(0, 1, 256)[None, :],
aspect='auto',
cmap='viridis',
origin='lower',
extent=[0, 1, 0, 1]
)
plt.show()
# Get unique values of primary_fuel
unique_fuels = df["primary_fuel"].unique()
# Generate colors for each type of fuel
fuel_colors = colormaps["viridis"](np.linspace(0, 1, len(unique_fuels)))
color_dict = {fuel: color for fuel, color in zip(unique_fuels, fuel_colors)}
# Generate shapes for each type of fuel
shapes = ["o", "s", "*", "D", "^", "v", "P", "X"]
shape_dict = {fuel: shapes[i % len(shapes)] for i, fuel in enumerate(unique_fuels)}
# Ensure that we are not working on a slice of the DataFrame
df = df.copy()
# Assign a color and shape to each data point
df["color"] = df["primary_fuel"].map(color_dict)
df["shape"] = df["primary_fuel"].map(shape_dict)
3.6 定义一个绘图函数
通过改变 central_longitude
参数,调整看地球的视角。
def generate_frame(lon_0):
plt.clf()
# Set up the map projection with the updated central longitude
ax = plt.axes(
projection=ccrs.Orthographic(central_longitude=lon_0, central_latitude=30)
)
# Set the extent to cover the entire globe to avoid cutting the edges
# This is not strictly necessary for Orthographic projection but can be used to avoid issues
ax.set_global()
# Draw coastlines, borders, and add features
ax.add_feature(cfeature.COASTLINE, linewidth=0.7)
# ax.add_feature(cfeature.LAND, color="lightgrey")
# ax.add_feature(cfeature.OCEAN, color="lightblue")
# Plot the power plants
for fuel in unique_fuels:
subset = df[df["primary_fuel"] == fuel]
x, y = subset["longitude"].values, subset["latitude"].values
ax.scatter(
x,
y,
color=color_dict[fuel], # Use color keyword-argument
label=fuel,
marker=shape_dict[fuel],
# edgecolor="k",
s=5,
alpha=1,
transform=ccrs.PlateCarree(),
)
# Add legend and title
plt.legend(loc="lower left", frameon=False)
plt.title(f"Global Power Plant Distribution - Lon: {lon_0}")
3.6.1 测试自定义的函数
# Start the timer
st = time.time()
# Test the function
plt.figure(figsize=(8, 8), dpi=300)
generate_frame(0)
plt.show()
# Stop the timer and print the elapsed time
et = time.time()
print(f"Run time {et - st} seconds.")
Run time 0.9506402015686035 seconds.
3.7 制作动图
# Start the timer
st = time.time()
# Create the animation
fig = plt.figure(figsize=(8, 8))
# Reduce the step size to make the animation more fluid
lon_0_values = np.arange(-180, 180, 2)
ani = FuncAnimation(fig, generate_frame, frames=lon_0_values, repeat=True)
# Save the animation as a GIF
# You might want to increase the fps for a smoother animation
ani.save("global_power_plants.gif", writer=PillowWriter(fps=12))
# Stop the timer and print the elapsed time
et = time.time()
print(f"Animation created in {et - st} seconds.")
4 结语
记录之。
脚注
https://wri-dataportal-prod.s3.amazonaws.com/manual/global_power_plant_database_v_1_3↩︎