我有三列数据:两个位置值和一个数据值。我想对这些数据进行透视,以便一列的元素成为新列,而另一列的元素成为索引。这些数据将使用 pcolormesh 绘制。 pcolormesh 期望数据结构化,这样它就不必猜测要做什么。即如果有一列nans,pcolormesh将不会正确填写这一列。因此,我编写了一些代码来正确调整数据形状,以便将其馈送到 pcolormesh。
我遇到的问题是代码似乎删除了 x = 0.0 周围的数据。我认为这是在重新索引数据框以包含“缺失”行的行上发生的。
我添加了一个图(因此添加了一些额外的代码)来为问题陈述提供视觉帮助。左图显示原始数据,右图显示为 pcolormesh reshape 数据后的结果。
我提供的代码示例只需复制和粘贴即可在 ipython 笔记本中运行。
欢迎提出任何建议。也许这个解决方案 super 复杂?确实有这种感觉。
%matplotlib inline
import decimal
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
test_df = pd.DataFrame()
test_df['x'] = [-2, -1.5, -0.9, -0.7, -0.5, 0.0, 0.5, 1.1]
test_df['y'] = [1,2,4,5,6,7,5,4]
test_df['v'] = np.random.randn(8)
def get_precision(number):
"""
gives the precision, or decimal place, of the number
http://stackoverflow.com/questions/6189956/easy-way-of-finding-decimal-places
"""
return int(abs(decimal.Decimal(str(number)).as_tuple().exponent))
def min_max(column):
column_min = np.floor(column.min())
column_max = np.ceil(column.max())
return column_min, column_max
def construct_df_for_pcolormesh(df, col, ix, values, columns_increment, index_increment):
columns_increment = 1.0/columns_increment
index_increment = 1.0/index_increment
columns_precision = get_precision(columns_increment)
index_precision = get_precision(index_increment)
columns_min, columns_max = min_max(df[col])
index_min, index_max = min_max(df[ix])
columns = np.linspace(columns_min, columns_max, (columns_max - columns_min)*columns_increment + 1)
index = np.linspace(index_min, index_max, (index_max - index_min)*index_increment + 1)
new_index = [(round(c, columns_precision), round(i, index_precision)) for c in columns for i in index]
df_for_pcolormesh = df.set_index([col, ix]).reindex(new_index).reset_index()
df_for_pcolormesh = df_for_pcolormesh.pivot(index=ix, columns=col, values=values)
return df_for_pcolormesh
fig, (ax,ax1)= plt.subplots(1,2, sharey=True, sharex=True)
test_df.plot(kind='scatter', x='x', y='y', s=100, grid=True, ax=ax)
ax.set_ylim(0,8)
ax.set_xlim(-2.5, 1.5)
ax.set_title('Plot with all the data')
data_df = construct_df_for_pcolormesh(test_df, 'x', 'y', 'v', 0.1, 0.1)
depths = data_df.index
xx = data_df.columns
d, x = np.meshgrid(depths, xx)
data = np.ma.masked_invalid(data_df.values)
ax1.pcolormesh(x, d, data.transpose(), cmap='viridis')
ax1.grid(True)
ax1.set_ylim(0,8)
ax1.set_xlim(-2.5, 1.5)
ax1.set_title('Plot with missing\ndatapoint at x=0.0')
请您参考如下方法:
我不确定真正的原因。但是,我将您的 min_max 函数更改为:
def min_max(column):
column_min = np.floor(column.min())
column_max = np.ceil(column.max()) + 1
return column_min, column_max
然后它起作用了:
