基于Python实现含降雨动画的图表:替换随机数为多年降雨数据
Got it, let's walk through how to swap out those random values with your actual yearly rainfall data, and tweak the plot to show rainfall magnitude and frequency clearly.
1. First, Get Your Data Structured
First off, make your rainfall data easy to load—CSV is the simplest format. Your file should have at least these columns (add extras if you need grouping, like region):
year,rainfall_mm,region 2010,56.2,North 2011,78.9,North 2012,45.1,South 2013,92.3,South 2014,62.7,North ...
2. Load Your Data into Python
We'll use pandas to read and handle the data (install it first if you haven't: pip install pandas). Here's how to load it:
import pandas as pd # Replace with your actual file path df = pd.read_csv('your_rainfall_data.csv') # Quick check to make sure data loaded correctly print(df.head())
3. Map Real Data to Plot Parameters
Let's replace each random parameter from the example with meaningful real values:
x: Use theyearcolumn to show rainfall over time (makes sense for yearly data)y: To mimic a "rainfall" effect, set this to a small random range (like 4-6) so points look like they're falling in a vertical band, or fix it to a single value if you want a neat horizontal linesize: Directly use therainfall_mmvalues—scale them up/down so points are visible but not overwhelminggroup: Group by rainfall intensity (split into bins) or by a category like region, to add color coding
Here's the updated code:
from lightning import Lightning import pandas as pd import numpy as np # Load your data df = pd.read_csv('your_rainfall_data.csv') # Sort by year to keep time order correct df = df.sort_values('year') # Assign plot parameters x = df['year'] # Random y values in a small range to look like rain falling y = np.random.uniform(4, 6, len(df)) # Group rainfall into 5 intensity bins (adjust bins to fit your data) df['rainfall_group'] = pd.cut(df['rainfall_mm'], bins=5, labels=[0, 1, 2, 3, 4]) group = df['rainfall_group'].astype('int') # Scale rainfall values to get reasonable point sizes size = df['rainfall_mm'] * 1.5 # Tweak the multiplier for better visibility # Create the scatter plot lgn = Lightning() lgn.scatter(x, y, group=group, size=size, title='Yearly Rainfall Intensity')
4. Add Rainfall Animation
To make it look like rain is falling over time, we can append points one by one in chronological order:
# Initialize an empty scatter plot first rain_chart = lgn.scatter([], [], group=[], size=[], title='Rainfall Animation') # Loop through each year's data and add points with a delay import time for _, row in df.iterrows(): # Add a single point for the year rain_chart.append( x=row['year'], y=np.random.uniform(4, 6), group=row['rainfall_group'], size=row['rainfall_mm'] * 1.5 ) # Adjust the sleep time to control animation speed (0.5s per point here) time.sleep(0.5)
Quick Tips to Polish the Plot
- If you have daily/hourly rainfall data, convert your date column to datetime first:
df['date'] = pd.to_datetime(df['date'])and use that forx - Tweak the
sizemultiplier until points look right—too big and they'll overlap, too small and you can't see differences - Customize colors for groups using the
colorparameter inlgn.scatter()to make intensity levels more intuitive (e.g., dark blue for heavy rain, light blue for light rain)
内容的提问来源于stack exchange,提问作者mikebun2

