如何用matplotlib可视化可读的大数据集?

0 投票
1 回答
30 浏览
提问于 2025-04-12 06:35

在用Python处理大数据集时,图表和日期常常变得难以阅读。怎么才能确保数据始终保持可读呢?欢迎任何解决方案,包括使用其他工具包。

我的代码:


import json
import matplotlib.pyplot as plt

# Load the JSON data from the file
with open('sorted_data.json', 'r') as file:
    sorted_data = json.load(file)

# Create a list of dates and corresponding values for each number
dates = list(sorted_data.keys())[:150]
numbers = list(sorted_data.values())[:150]

# Set a larger figure size
plt.figure(figsize=(10, 6))  # Adjust the width and height as needed

# Create a scatter plot for each date
for i in range(len(dates)):
    date = dates[i]
    number_values = list(numbers[i].values())
    plt.scatter([date]*7, list(numbers[i].values()), label=date)

# Adding labels and title
plt.xlabel('Dates')
plt.ylabel('Values')
plt.title('Visualization of Sorted JSON Data')
plt.xticks(rotation=45)  # Rotate the x-axis labels for better visibility
plt.legend()  # Show the legend

# Display the plot
plt.show()

Json示例:

{
    "2000-01-01": {
        "n1": 9,
        "n2": 19,
        "n3": 22,
        "n4": 39,
        "n5": 41,
        "n6": 42,
        "n7": 17
    },
    "2000-01-05": {
        "n1": 9,
        "n2": 13,
        "n3": 14,
        "n4": 22,
        "n5": 23,
        "n6": 39,
        "n7": 18
    },...
}

输出结果:

代码的输出结果:

我在尝试用Python可视化大数据集,希望它始终能保持可读性。

1 个回答

2

问题不在于matplotlib能做什么,而在于你让它做了什么。

在导入数据时,你把日期字符串当作普通字符串处理,这样它们就变成了分类数据。matplotlib对此无能为力,无法让图表保持可读性。

你可能想要的是在时间轴上绘制数据。为此,你需要在导入时将字符串解析成datetime对象。

dates = [dt.datetime.strptime(k,'%Y-%m-%d') for k in sorted_data.keys()]

第二个问题是,你为每个日期请求一个单独的散点图。其实你可能想要的是为你的json中的每个键绘制图表。

为了做到这一点,我们需要重新整理输入数据,将每个n1n2等值列出。为了方便,我们可以把它们存储在字典里。

dates_dict = {}
numbers_dict = {}
for date,vs, in sorted_data.items():
    for k,v in vs.items():
        if not k in numbers_dict.keys():
            # create lists on first call
            dates_dict[k] = []
            numbers_dict[k] = []
        dates_dict[k].append(dt.datetime.strptime(date,'%Y-%m-%d'))
        numbers_dict[k].append(v)

# Create a scatter plot for each date
for key in numbers_dict.keys():
    plt.scatter(dates_dict[key], numbers_dict[key], label=key)

这样,图表就会为每个键使用一种颜色:

这里输入图片描述

撰写回答