3.Python数据可视化_ 下载数据

下载数据

1. CSV文件格式

  • 要在文本文件中存储数据,一个简单方式是将数据作为一系列以逗号分隔的值(comma-separated-values)写人文件。这样的文件称为CSV文件
  • 例如: "USW00025333", "SITKA AIRPORT, AK US", "2018-01-01", "0.45"

1. 分析CSV文件头

import csv

filename = './sitka_weather_07-2018_simple.csv'
with open(filename) as f:  # 打开CSV文件夹并将返回的文件对象赋值给 f
    reader = csv.reader(f)  # 创建一个与该文件相关的阅读器对象, 这样操作才可以让Python知道如何处理CSV文件
    header_row = next(reader)  # 调用它并传入阅读器对象时, 他讲返回文件的下一行
    # 因为next()只被调用了一次所以只读了文件的第一行
    print(header_row)

2. 打印文件头及其位置

import csv

filename = './sitka_weather_07-2018_simple.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

for index, column_header in enumerate(header_row):  # 这个函数的意思为获取每个元素的索引及其值
    print(index, column_header)

3. 提取并读取数据

import csv

filename = './sitka_weather_07-2018_simple.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

# 从文本中获取最高温度
    highs = []
    for row in reader:  # 阅读器对象从其停留的地方急需向下读取CSV文件, 每次自动返回当前所处位置的下一行
        # 因为已经在上边读取了CSV文件的第一行 所以他会从第二行开始循环
        high = int(row[5])  # 获取当前行的索引为5(TMAX行)的值, 因为存储的为字符串类型, 所以要转化为Int类型
        highs.append(high)

print(highs)

4. 绘制温度图表

import csv
import matplotlib.pyplot as plt

filename = './sitka_weather_07-2018_simple.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

# 从文本中获取最高温度
    highs = []
    for row in reader:  # 阅读器对象从其停留的地方急需向下读取CSV文件, 每次自动返回当前所处位置的下一行
        # 因为已经在上边读取了CSV文件的第一行 所以他会从第二行开始循环
        high = int(row[5])  # 获取当前行的索引为5(TMAX行)的值, 因为存储的为字符串类型, 所以要转化为Int类型
        highs.append(high)


# 根据最高温绘制图表
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(highs, c='red')

# 设置图形格式
ax.set_title("2018年七月每日最高温度", fontsize=24)
ax.set_xlabel('', fontsize=16)
ax.set_ylabel('温度(F)', fontsize=16)
ax.tick_params(axis='both', which='major', labelsize=16)

plt.show()

5. 模块datetime

  • datetime.strptime('2018-07-01', '%Y-%m-%d')
  • 首先导入模块datetime中的datetime类,再调用方法strptime(),并将包含所需日期的字符串作为第一个实参。第二个实参告诉Python如何设置日期的格式。在这里,让Python将字符串中第一个连字符前面的部分视为四位的年份,'%m-'让Python将第二个连字符前面的部分视为表示月份的数,'%d'让Pyho咖将字符串的最后一部分视为月份中的一天(1~31)。
  • 方法strptime()可接受各种实参,并根据它们来决定如何解读日期。

6. 在图表中添加日期

import csv
import matplotlib.pyplot as plt
from datetime import datetime

filename = './sitka_weather_07-2018_simple.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

# 从文本中获取最高温度
    highs = []
    datas = []
    for row in reader:  
        current_data = datetime.strptime(row[2], '%Y-%m-%d')  # 获取时间信息
        high = int(row[5])  
        highs.append(high)
        datas.append(current_data)


# 根据最高温绘制图表
plt.style.use('seaborn-v0_8')
fig, ax = plt.subplots()
ax.plot(datas, highs, c='red')

# 设置图形格式
ax.set_title("Maximum daily temperature in July 2018", fontsize=24)
ax.set_xlabel('', fontsize=16)
fig.autofmt_xdate()  # 绘制倾斜的日期, 以免覆盖
ax.set_ylabel('Temperature(F)', fontsize=16)
ax.tick_params(axis='both', which='major', labelsize=16)

plt.show()

7. 在绘制一个数据系列

import csv
import matplotlib.pyplot as plt
from datetime import datetime

filename = './sitka_weather_07-2018_simple.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

# 从文本中获取最高温度
    highs = []
    dates = []
    lows = []  # 最低温度
    for row in reader:
        current_date = datetime.strptime(row[2], '%Y-%m-%d')  # 获取时间信息
        high = int(row[5])
        low = int(row[6])
        highs.append(high)
        dates.append(current_date)
        lows.append(low)

# 根据最高温绘制图表
plt.style.use('seaborn-v0_8')
fig, ax = plt.subplots()
ax.plot(dates, highs, c='red')  # 绘制最高温度
ax.plot(dates, lows, c='blue')  # 绘制最低温度
# 设置图形格式
ax.set_title("Daily temperature in 2018", fontsize=24)
ax.set_xlabel('', fontsize=16)
fig.autofmt_xdate()  # 绘制倾斜的日期, 以免覆盖
ax.set_ylabel('Temperature(F)', fontsize=16)
ax.tick_params(axis='both', which='major', labelsize=16)

plt.show()

8. 给图表区域着色

  • 使用fill_between()方法

  • import csv
    import matplotlib.pyplot as plt
    from datetime import datetime
    
    filename = './sitka_weather_07-2018_simple.csv'
    with open(filename) as f:
        reader = csv.reader(f)
        header_row = next(reader)
    
    # 从文本中获取最高温度
        highs = []
        dates = []
        lows = []
        for row in reader:
            current_date = datetime.strptime(row[2], '%Y-%m-%d')  # 获取时间信息
            high = int(row[5])
            low = int(row[6])
            highs.append(high)
            dates.append(current_date)
            lows.append(low)
    
    # 根据最高温绘制图表
    plt.style.use('seaborn-v0_8')
    fig, ax = plt.subplots()
    ax.plot(dates, highs, c='red', alpha=0.5)  # alpha指的是颜色的透明度
    ax.plot(dates, lows, c='blue', alpha=0.5) 
    ax.fill_between(dates, highs, lows, facecolor='blue', alpha=0.5)  # 进行填色
    # 设置图形格式
    ax.set_title("Daily temperature in 2018", fontsize=24)
    ax.set_xlabel('', fontsize=16)
    fig.autofmt_xdate()
    ax.set_ylabel('Temperature(F)', fontsize=16)
    ax.tick_params(axis='both', which='major', labelsize=16)
    
    plt.show()
    
    

2. 制作全球地震散点图: JSON格式

1. 创建地震列表

import json

# 探索数据结构
filename = './eq_data_1_day_m1.json'
with open(filename) as f:
    all_ep_date = json.load(f)  # 读取文件并让变量指向它

all_ep_dicts = all_ep_date['features']  # 查看JSON文件可知是个列表
print(len(all_ep_dicts)  # 获取到一共地震了多少

2. 提取震级

import json

# 探索数据结构
filename = './eq_data_1_day_m1.json'
with open(filename) as f:
    all_ep_date = json.load(f)

all_ep_dicts = all_ep_date['features']

# 获取震级
mags = []
for eq_dict in all_ep_dicts:
    mag = eq_dict['properties']['mag']
    mags.append(mag)

print(mags)

3. 获取位置数据

import json

# 探索数据结构
filename = './eq_data_1_day_m1.json'
with open(filename) as f:
    all_ep_date = json.load(f)

all_ep_dicts = all_ep_date['features']

# 获取震级
mags = []
titles = []
lons = []
lats = []
for eq_dict in all_ep_dicts:
    mag = eq_dict['properties']['mag']
    mags.append(mag)

    # 获取位置信息
    title = eq_dict['properties']['title']
    lon = eq_dict['geometry']['coordinates'][0]
    lat = eq_dict['geometry']['coordinates'][1]
    titles.append(title)
    lons.append(lon)
    lats.append(lat)
    

4. 绘制震级散点图

import json
import plotly.express as px
# 探索数据结构
filename = './eq_data_1_day_m1.json'
with open(filename) as f:
    all_ep_date = json.load(f)

all_ep_dicts = all_ep_date['features']

# 获取震级
mags = []
titles = []
lons = []
lats = []
for eq_dict in all_ep_dicts:
    mag = eq_dict['properties']['mag']
    mags.append(mag)

    # 获取位置信息
    title = eq_dict['properties']['title']
    lon = eq_dict['geometry']['coordinates'][0]
    lat = eq_dict['geometry']['coordinates'][1]
    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('global_earthquakes.html')
fig.show()

就暂时到这吧.....以后接触数据处理时在详细的学学, 可视化

posted @   VarFa  阅读(142)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示