用pandas做全球温度变化可视化

废话不多说,以下是代码,感兴趣的可以copy后自行下载数据到你本地运算。

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

def draw_scatter_2d(xtick,ytick,xtickmax,ytickmax,xlabel,ylabel,title,xtick_rotation_angle,df,path_for_saving):
    # Create a scatter plot
    fig, ax = plt.subplots(figsize=(12,6)) 
    ax.scatter(df[xtick],df[ytick])
   
    # Set the x-tick locator 
    ax.xaxis.set_major_locator(plt.MaxNLocator(xtickmax))
    
    # Set the y-tick locator
    ax.yaxis.set_major_locator(plt.MaxNLocator(ytickmax))
    
    if df[xtick].dtype == 'datetime64[ns]':
        # Convert the date_str column to a numerical format
        df.loc[:,'date_num'] = mdates.date2num(pd.to_datetime(df[xtick]))
        
        # Set the x-axis scale to a standard date format
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
        
    if df[ytick].dtype == 'datetime64[ns]':
        # Convert the date_str column to a numerical format
        df.loc[:,'date_num'] = mdates.date2num(pd.to_datetime(df[ytick]))
        
        # Set the y-axis scale to a standard date format
        ax.yaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    
    # Set the labels for each axis
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_title(title)

    # Set the x-axis scale to a standard date format
    #ax.xaxis.set_major_formatter('%Y-%m-%d')
    
    # Rotate the x-axis labels
    ax.tick_params(axis='x', rotation=xtick_rotation_angle, labelsize=9)  # Decrease the font size
    plt.rcParams['font.sans-serif'] = ['Times New Roman']
    #plt.xticks(rotation=xtick_rotation_angle)

    # Show the plot
    #plt.show()
    plt.savefig(path_for_saving)
    plt.close()

file_path = r'GlobalTemperatures.csv'
# Read the data into a pandas DataFrame
df = pd.read_csv(file_path, delimiter=',')

draw_scatter_2d(
  							df.columns[0],
                df.columns[1],
                30,30,
                'Date','Average Temperature',
                'Average Global Land & Ocean Temperature',
                60,
                df,
                'GlobalLandAndOceanTemperature.png'
)

展开阅读全文

页面更新:2024-04-14

标签:废话   温度   代码   数据   全球

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top