我有以下pandas Dataframe if (error === "AUTH_REQUIRED") {
//halt default event then initiate state go to new nested page
event.preventDefault();
// as of now, we go to login until landing template is up
$state.go("home");
}
:
df
我想创建一个十六进制bin图,其中x轴使用列名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 ║
╚════╩═════╩═════╝
,y轴使用标记(x1, x2)
。数据框中的数字代表计数,例如数字越大,十六进制的颜色越深。
理想情况是这样的:
(y1, y2)
有机会以简单的方式做到这一点吗?
答案 0 :(得分:1)
考虑虚拟数据帧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)
<强> 绘图: 强>
将值传递给六边形bin图的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
]