我有以下 Pandas 数据框df:
import pandas as pd
from decimal import Decimal
df = pd.DataFrame([[1, Decimal('nan')], [100, 10]], index=['y1', 'y2'], columns=['x1', 'x2'])
╔════╦═════╦═════╗
║ ║ x1 ║ x2 ║
╠════╬═════╬═════╣
║ y1 ║ 1 ║ NAN ║
║ y2 ║ 100 ║ 10 ║
╚════╩═════╩═════╝
我想创建一个十六进制图,其中 x 轴使用列名 (x1, x2),y 轴使用索引 (y1, y2)。 Dataframe 中的数字代表计数,例如数字越大,十六进制的颜色越深。 所以理想情况下是这样的:
df.plot.hexbin(x=df.columns, y=df.index.get_values())
有机会以简单的方式做到这一点吗?
请您参考如下方法:
考虑一个虚拟数据框,DF:
from matplotlib.ticker import FuncFormatter
np.random.seed(314)
dummy_df = pd.DataFrame(np.random.randint(0, 100, (10, 3)), columns=['x1', 'x2', 'x3'],
index=['y{}'.format(i) for i in range(1, 11)])
Melt DF 有一个列分别对应于索引、列和值:
df = pd.melt(dummy_df.reset_index(), id_vars=['index'])
仅采用字符串的数字部分来帮助绘制 hexbin 图的 x 轴和 y 轴。
df['index_int'] = df['index'].str.extract('(\d+)', expand=False).astype(int)
df['variable_int'] = df['variable'].str.extract('(\d+)', expand=False).astype(int)
绘图:
将值传递给六边形箱图的 C arg,它指定每个 (x, y) 点的值:
fig, ax = plt.subplots()
hex_ax = ax.hexbin(x=df['variable_int'], y=df['index_int'], C=df['value'],
gridsize=10, cmap=plt.cm.Reds)
fig.colorbar(hex_ax)
ax.xaxis.set_major_formatter(FuncFormatter(lambda x, _: 'x{:.0f}'.format(x)))
ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: 'y{:.0f}'.format(y)))
plt.xticks(np.unique(df['variable_int'].values))
plt.show()
注意:如果您使用数据帧的 hexbin 内置图,xticks 和 xlabels 不会出现在结果图中,因此它等同于 调用了 matplotlib hexbin 方法。[参见 GH issue ]
