【问题标题】:Python - Plotting Historical Temperature DataPython - 绘制历史温度数据
【发布时间】:2018-02-15 21:10:12
【问题描述】:

我目前正在研究 1815 年坦博拉火山喷发如何导致所谓的“无夏之年”,并且需要一些绘制数据的帮助。

我有一个来自气象站的文本文件,它提供了我感兴趣的年份 (1816) 的每日温度数据。文件中的每一列代表月份,从 1 月到 12 月,(第一行除外),每一行是该月中的某一天;

1  -22    5   52   82  102  155  176  168  100  114   89   54
2  -31   21   68  107  139  177  146  159   90  118   85   74
3  -49   41   63  103  170  134  144  140  106   99   86   63
4  -52   56   77  109  180  137  153  136  105  105   52   90
5  -66   75   67  103  169  165  160  145  102   90   62   74
6  -35   80   60   82  121  152  173  131  123   96   86   60
7  -17   69   34   91  128  175  195  125  139  103   75   65
8   -7   80  -17   79  152  161  135  134  148  104   34   64

我对 Python 比较陌生,但当然可以做基本的绘图...但是这里显示数据的方式让我有点难过!我想绘制的是全年,x 轴上的天/月,y 轴上的温度值,在一个图表上。这样我就可以将今年与其他年份进行比较!

我可以做一些基本的事情,比如选择代表一月的列并将所有 -999 值设置为 nan,即

d = np.loadtxt("test.txt")
January = d[:,1]
January[January <= -999] = np.nan

但是很难想出一种方法来按照我想要的方式绘制所有数据。

任何帮助将不胜感激!

【问题讨论】:

  • 恕我直言 weathergraph 在这里是不相关的标签。我宁愿使用matplotlibpandas

标签: python plot graph weather


【解决方案1】:

将文本文件读入 pandas 数据框。然后您可以将其拆开,这将连续产生一系列的所有日期。

import pandas as pd

# read text-file
df = pd.read_csv('test.txt', sep='  ')

# drop the first column in your text file
df = df.drop(df.columns[0], axis=1)

# unstack to make a series of the days
df = df.unstack()

# remove na that will come from months with less than 31 days
df = df.dropna()

# plot with pandas
df.plot()

【讨论】:

  • 您好,卡尔,感谢您这么快回复!不幸的是,pandas 不是我在基本编码课程中被教导使用的东西,但看起来很适合这个!但是,当我使用此方法时,我遇到一条错误消息:'ValueError: Expected 14 fields in line 2, saw 15'...知道为什么会发生这种情况吗?
  • 正如错误消息所说,您的文本的第二行似乎有 15 个项目,而第一行只有 14 个。我想这与文件中列之间的分隔符有关。检查有关如何从 text/csv 读取到 pandas 的答案:stackoverflow.com/questions/21546739/… 我不知道您的文本文件中是否有任何列名。如果不是,read_csv 提供了一个很好的功能,可以在读取文件时添加列名。
【解决方案2】:

这是执行此操作的代码:

import numpy as np
import matplotlib.pyplot as plt

temp_data = np.loadtxt("plot_weather_data.txt")
num_days = len(temp_data)
temperature = []

# for each of the days
for index_days in range(0, num_days-1):
#     for each of the months
    for index_month in range(1, 13):
#         starting from the second column, append the value to a list
        temperature.append(temp_data[index_days][index_month])

# call matplot lib and plot the graph
plt.plot(temperature)
plt.ylabel("temperature [C]")
plt.show()

您还可以在此处找到名为 plot_weather_data.txt 的文本文件以及上述文件:https://github.com/alphaCTzo7G/stackexchange/blob/master/python/plot_temp.py

【讨论】:

  • 您好 alpha_989,感谢您的回复!这确实从我的数据中提供了一个图,但是我注意到它将数据绘制为每个月的所有第一天数据,然后是每个月的所有第二天数据等等......(如果这有意义吗?)。我想要的是,基本上,1 月 1 日、2 日、3 日……然后是 2 月的数据,一直到 12 月(最后一列)的数据。有任何想法吗?再次感谢!
猜你喜欢
  • 2015-11-14
  • 1970-01-01
  • 2019-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多