python - Matplotlib:来自 3 列 pandas 数据帧的 pcolormesh 或 pcolor

标签 python pandas matplotlib

我有一个文件“mydata.tmp”,其中包含 3 列,如下所示:

3.81107 0.624698 0.000331622 
3.86505 0.624698 0.000131237 
3.91903 0.624698 5.15136e-05 
3.97301 0.624698 1.93627e-05 
1.32802 0.874721 1.59245 
1.382   0.874721 0 
1.43598 0.874721 0 
1.48996 0.874721 4.27933 

等等

然后我想制作一个热图颜色图,其中前两列是坐标,第三列是该坐标的值。

另外,我想以对数刻度设置第三列。

我该怎么做?

我尝试使用散点类型的绘图来编写以下代码

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.read_csv('mydata.tmp', delim_whitespace=True, 
                     comment='#',header=None,
                     names=['a','b','c'])

fig, ax = plt.subplots()

sc = ax.scatter(df.a, df.b, c=df.c,  cmap="GnBu", s=400, 
     norm=matplotlib.colors.LogNorm())

fig.colorbar(sc, ax=ax)

plt.show()

我得到了下面显示的图片(忽略 x 轴的比例)。不过,我想得到当我使用此代码执行 GNUplot 时获得的结果(我还附加了 GNUplot 图像)

plot mydata.tmp using 1:2:3 with image

也许我必须使用 pcolormesh? 谢谢!

GNUplot 图像: GNUplot Image

Matplotlib 图像: Matplotlib Image

当我尝试 Khalil 代码时,我得到了这个图像: enter image description here

最佳答案

试试这个。对我拥有的一些数据进行了测试和处理。 间距非常重要。根据您想要的绘图网格进行设置。间距越大,图像越平滑,但计算时间较长。

import pandas as pd
import matplotlib.pyplot as plt
import scipy.interpolate
import numpy as np
import matplotlib.colors as colors

# import data
df = pd.read_csv('mydata.tmp', delim_whitespace=True, 
                     comment='#',header=None,
                     names=['1','2','3'])

x = df['1']
y = df['2']
z = df['3']

# Set up a regular grid of interpolation points

spacing = 500
xi, yi = np.linspace(x.min(), x.max(), spacing), np.linspace(y.min(), 
                     y.max(), spacing)

XI, YI = np.meshgrid(xi, yi)

# Interpolate
rbf = scipy.interpolate.Rbf(x, y, z, function='linear')

ZI = rbf(XI, YI)

#plot

fig, ax = plt.subplots()

sc = ax.imshow(ZI, vmin=z.min(), vmax=z.max(), origin='lower',
            extent=[x.min(), x.max(), y.min(), 
                    y.max()], cmap="GnBu", norm=colors.LogNorm(vmin=ZI.min(),
                    vmax=ZI.max()))

fig.colorbar(sc, ax=ax, fraction=0.05, pad=0.01)

plt.show()

关于python - Matplotlib:来自 3 列 pandas 数据帧的 pcolormesh 或 pcolor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52106307/

相关文章:

python selenium 多个测试用例

python - 如何在 C++ 中使用 CPR 库?

python - 带有\W+ 分隔符的意外 read_csv 结果

python - Pandas :从每行的随机列中选择值

python - 将数据框中的所有数字除以一个常数

matplotlib pyplot imshow 图像之间的紧密间距

python - 循环遍历大型 .tif 堆栈(图像光栅)并提取位置

python - 解析带有嵌套引号的字符串

python - Matplotlib 曲面图显示不同值的相同颜色

matplotlib - 从 Pandas 时间序列图中的Axes.get_xlim()获取可用日期