python - 具有两个分类变量的 Matplotlib 点图
问题描述
我想产生一种特定类型的可视化,由一个相当简单的点图组成,但有一个扭曲:两个轴都是分类变量(即序数或非数值)。这使事情变得复杂而不是使事情变得更容易。
为了说明这个问题,我将使用一个小型示例数据集,该数据集是这样修改seaborn.load_dataset("tips")
和定义的:
import pandas
from six import StringIO
df = """total_bill | tip | sex | smoker | day | time | size
16.99 | 1.01 | Male | No | Mon | Dinner | 2
10.34 | 1.66 | Male | No | Sun | Dinner | 3
21.01 | 3.50 | Male | No | Sun | Dinner | 3
23.68 | 3.31 | Male | No | Sun | Dinner | 2
24.59 | 3.61 | Female | No | Sun | Dinner | 4
25.29 | 4.71 | Female | No | Mon | Lunch | 4
8.77 | 2.00 | Female | No | Tue | Lunch | 2
26.88 | 3.12 | Male | No | Wed | Lunch | 4
15.04 | 3.96 | Male | No | Sat | Lunch | 2
14.78 | 3.23 | Male | No | Sun | Lunch | 2"""
df = pandas.read_csv(StringIO(df.replace(' ','')), sep="|", header=0)
我制作图表的第一种方法是尝试调用seaborn
如下:
import seaborn
axes = seaborn.pointplot(x="time", y="sex", data=df)
这失败了:
ValueError: Neither the `x` nor `y` variable appears to be numeric.
等价的seaborn.stripplot
和seaborn.swarmplot
调用也是如此。但是,如果其中一个变量是分类变量而另一个变量是数字变量,则它确实有效。确实seaborn.pointplot(x="total_bill", y="sex", data=df)
有效,但不是我想要的。
我还尝试了这样的散点图:
axes = seaborn.scatterplot(x="time", y="sex", size="day", data=df,
x_jitter=True, y_jitter=True)
这会产生以下图表,其中不包含任何抖动并且所有点都重叠,使其无用:
您知道可以解决我的问题的任何优雅方法或库吗?
我开始自己写一些东西,我将在下面介绍,但是这个实现不是最理想的,并且受到在同一点可以重叠的点数的限制(目前如果超过 4 个点重叠,它会失败)。
# Modules #
import seaborn, pandas, matplotlib
from six import StringIO
################################################################################
def amount_to_offets(amount):
"""A function that takes an amount of overlapping points (e.g. 3)
and returns a list of offsets (jittered) coordinates for each of the
points.
It follows the logic that two points are displayed side by side:
2 -> * *
Three points are organized in a triangle
3 -> *
* *
Four points are sorted into a square, and so on.
4 -> * *
* *
"""
assert isinstance(amount, int)
solutions = {
1: [( 0.0, 0.0)],
2: [(-0.5, 0.0), ( 0.5, 0.0)],
3: [(-0.5, -0.5), ( 0.0, 0.5), ( 0.5, -0.5)],
4: [(-0.5, -0.5), ( 0.5, 0.5), ( 0.5, -0.5), (-0.5, 0.5)],
}
return solutions[amount]
################################################################################
class JitterDotplot(object):
def __init__(self, data, x_col='time', y_col='sex', z_col='tip'):
self.data = data
self.x_col = x_col
self.y_col = y_col
self.z_col = z_col
def plot(self, **kwargs):
# Load data #
self.df = self.data.copy()
# Assign numerical values to the categorical data #
# So that ['Dinner', 'Lunch'] becomes [0, 1] etc. #
self.x_values = self.df[self.x_col].unique()
self.y_values = self.df[self.y_col].unique()
self.x_mapping = dict(zip(self.x_values, range(len(self.x_values))))
self.y_mapping = dict(zip(self.y_values, range(len(self.y_values))))
self.df = self.df.replace({self.x_col: self.x_mapping, self.y_col: self.y_mapping})
# Offset points that are overlapping in the same location #
# So that (2.0, 3.0) becomes (2.05, 2.95) for instance #
cols = [self.x_col, self.y_col]
scaling_factor = 0.05
for values, df_view in self.df.groupby(cols):
offsets = amount_to_offets(len(df_view))
offsets = pandas.DataFrame(offsets, index=df_view.index, columns=cols)
offsets *= scaling_factor
self.df.loc[offsets.index, cols] += offsets
# Plot a standard scatter plot #
g = seaborn.scatterplot(x=self.x_col, y=self.y_col, size=self.z_col, data=self.df, **kwargs)
# Force integer ticks on the x and y axes #
locator = matplotlib.ticker.MaxNLocator(integer=True)
g.xaxis.set_major_locator(locator)
g.yaxis.set_major_locator(locator)
g.grid(False)
# Expand the axis limits for x and y #
margin = 0.4
xmin, xmax, ymin, ymax = g.get_xlim() + g.get_ylim()
g.set_xlim(xmin-margin, xmax+margin)
g.set_ylim(ymin-margin, ymax+margin)
# Replace ticks with the original categorical names #
g.set_xticklabels([''] + list(self.x_mapping.keys()))
g.set_yticklabels([''] + list(self.y_mapping.keys()))
# Return for display in notebooks for instance #
return g
################################################################################
# Graph #
graph = JitterDotplot(data=df)
axes = graph.plot()
axes.figure.savefig('jitter_dotplot.png')
解决方案
您可以先将time
and转换sex
为分类类型并稍微调整一下:
df.sex = pd.Categorical(df.sex)
df.time = pd.Categorical(df.time)
axes = sns.scatterplot(x=df.time.cat.codes+np.random.uniform(-0.1,0.1, len(df)),
y=df.sex.cat.codes+np.random.uniform(-0.1,0.1, len(df)),
size=df.tip)
输出:
有了这个想法,您可以np.random
将上述代码中的偏移量 ( ) 修改为相应的距离。例如:
# grouping
groups = df.groupby(['time', 'sex'])
# compute the number of samples per group
num_samples = groups.tip.transform('size')
# enumerate the samples within a group
sample_ranks = df.groupby(['time']).cumcount() * (2*np.pi) / num_samples
# compute the offset
x_offsets = np.where(num_samples.eq(1), 0, np.cos(df.sample_rank) * 0.03)
y_offsets = np.where(num_samples.eq(1), 0, np.sin(df.sample_rank) * 0.03)
# plot
axes = sns.scatterplot(x=df.time.cat.codes + x_offsets,
y=df.sex.cat.codes + y_offsets,
size=df.tip)
输出:
推荐阅读
- c# - .net core COM 与 Excel 范围
- r - 使用字符串向量在 R 中循环自定义 ifelse 函数
- firebase - Google Firebase 的计划政策是“每个帐户”还是“每个项目”?
- r - 如何将此列表转换为每行都是单个实体的数据框
- c# - 在指定文化和源时区的同时将“Kind-less”日期时间转换为世界时间
- javascript - 多次调用函数但丢失过去的数据
- office365 - SysWow64 中的 ActiveX 控件不适用于 Excel
- flutter - 如何将唯一 ID 或密钥分配给 SwitchListTile 并在颤动移动应用程序的 onChanged 中检索/获取其值
- javascript - 如何在 JavaScript 中为特定列表加下划线
- java - 使用 Tomcat 获取 AccessDeniedException?