awc*_*olm 5 python matplotlib pandas
我试图控制 matplotlib 散点图上的 y 轴顺序,但我所拥有的数据中 x 轴和 y 轴的顺序导致绘图显示不正确。
下面是一些代码来说明问题以及提出解决方案的次优尝试。
import pandas as pd
from numpy import random
import matplotlib.pyplot as plt
# make some fake data
axes = ['a', 'b', 'c', 'd']
pairs = pd.DataFrame([(x, y) for x in axes for y in axes], columns=['x', 'y'])
pairs['value'] = random.randint(100, size=16) + 100
# remove the diagonal
pairs_nodiag = pairs[pairs['x'] != pairs['y']]
# zero the values for the diagonal
pairs_diag = pairs.copy()
pairs_diag.loc[pairs_diag['x'] == pairs_diag['y'], 'value'] = 0
fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(5, 3))
scatter = ax[0].scatter(x=pairs['x'], y=pairs['y'], s=pairs['value'])
scatter = ax[1].scatter(x=pairs_nodiag['x'], y=pairs_nodiag['y'], s=pairs_nodiag['value'])
scatter = ax[2].scatter(x=pairs_diag['x'], y=pairs_diag['y'], s=pairs_diag['value'])
plt.show()
Run Code Online (Sandbox Code Playgroud)
最左边是原始数据。中间是有问题的情节;我希望 y 轴与最左边的图相同。最右边的图是我使用次优解决方法后的结果。我确信有一种方法可以控制轴上的顺序,但我在 Python 方面还不够专业,还不知道到底如何做到这一点。
您需要使用所需的映射创建自己的StringCategoryConverter(matplotlib 默认情况下将字符串按出现的顺序映射到数字)。
import matplotlib.category as mcat
# insert the following before scatter = ax[1].scatter(...
units = mcat.UnitData(sorted(pairs_nodiag.y.unique()))
ax[1].yaxis.set_units(units)
ax[1].yaxis.set_major_locator(mcat.StrCategoryLocator(units._mapping))
ax[1].yaxis.set_major_formatter(mcat.StrCategoryFormatter(units._mapping))
Run Code Online (Sandbox Code Playgroud)
更新:以下是不使用的官方方法_mapping:
import matplotlib
# insert the following before scatter = ax[1].scatter(...
scc = matplotlib.category.StrCategoryConverter()
units = scc.default_units(sorted(pairs_nodiag.y.unique()), ax[1].yaxis)
axisinfo = scc.axisinfo(units, ax[1].yaxis)
ax[1].yaxis.set_major_locator(axisinfo.majloc)
ax[1].yaxis.set_major_formatter(axisinfo.majfmt)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1508 次 |
| 最近记录: |