当我要绘制枢轴数据帧的热图时
import pandas as pd
import seaborn as sns
%matplotlib inline
sample = pd.DataFrame.from_dict({'x': np.tile(np.arange(2,5),(1,5))[0],
'y': np.tile(np.arange(0,5),(1,3))[0],
'value': np.random.rand(15)
})
sample_pvt = sample.pivot_table(index='x',columns='y')
plt.pcolor(sample_pvt)
即使x的范围是2到5,该图也只显示0到3的范围。我知道使用seaborn可以解决问题,但是有没有办法在pcolor中指定轴范围?谢谢
答案 0 :(得分:1)
Seaborn会简单地注释pcolor(mesh)图的行和列。要在这里达到相同的目的,
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
sample = pd.DataFrame.from_dict({'x': np.tile(np.arange(2,5),(1,5))[0],
'y': np.tile(np.arange(0,5),(1,3))[0],
'value': np.random.rand(15)
})
sample_pvt = sample.pivot_table(index='x',columns='y')
sample_pvt.columns = sample_pvt.columns.droplevel(0)
plt.pcolor(sample_pvt)
plt.xticks(np.arange(len(sample_pvt.columns))+0.5, sample_pvt.columns)
plt.yticks(np.arange(len(sample_pvt.index))+0.5, sample_pvt.index)
plt.show()
要改为以正确的数字方式放置像素,您需要首先确定x和y值实际上是像素的中心还是边缘。对于中心,
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np; np.random.seed(42)
sample = pd.DataFrame.from_dict({'x': np.tile(np.arange(2,5),(1,5))[0],
'y': np.tile(np.arange(0,5),(1,3))[0],
'value': np.random.rand(15)
})
sample_pvt = sample.pivot_table(index='x',columns='y')
sample_pvt.columns = sample_pvt.columns.droplevel(0)
x = np.linspace(sample_pvt.columns[0]-0.5, sample_pvt.columns[-1]+0.5, len(sample_pvt.columns)+1)
y = np.linspace(sample_pvt.index[0]-0.5, sample_pvt.index[-1]+0.5, len(sample_pvt.index)+1)
plt.pcolor(x, y, sample_pvt)
plt.show()
对于边缘,
x = np.linspace(sample_pvt.columns[0], sample_pvt.columns[-1]+1, len(sample_pvt.columns)+1)
y = np.linspace(sample_pvt.index[0], sample_pvt.index[-1]+1, len(sample_pvt.index)+1)
plt.pcolor(x, y, sample_pvt)