在FacetGrid和双Y轴中结合 pandas [英] Combining FacetGrid and dual Y-axis in Pandas
问题描述
我试图在单个FacetGrid上绘制两个不同的变量(通过因果关系链接),delai_jour
和date_sondage
.我可以用下面的代码做到这一点:
I am trying to plot two different variables (linked by a relation of causality), delai_jour
and date_sondage
on a single FacetGrid. I can do it with this code:
g = sns.FacetGrid(df_verif_sum, col="prefecture", col_wrap=2, aspect=2, sharex=True,)
g = g.map(plt.plot, "date_sondage", "delai_jour", color="m", linewidth=2)
g = g.map(plt.bar, "date_sondage", "impossible")
这给了我这个
(共有33个).
我有兴趣比较各种prefecture
上的图形,但是由于幅度的差异,我看不到折线图中的变化.
I'm interested in comparing the patterns across the various prefecture
, but due to the difference in magnitude I cannot see the changes in the line chart.
对于此特定工作,最好的方法是创建第二个y轴,但我似乎无济于事:FacetGrid看起来不可行,而且我不明白该代码无法复制使用纯matplotlib看到的示例.
For this specific work, the best way to do it is to create a secondary y axis, but I can't seem to make anything work: it doesn't look like it's possible with FacetGrid, and I didn't understand the code not was able to replicate the examples i've seen with pure matplotlib.
我应该怎么做?
推荐答案
在此示例中,您将自定义映射函数应用于目标数据框.在函数内,您可以调用plt.gca()
来获取FacetGrid中当前绘制的构面上的当前轴.一旦有了轴,就可以像在普通的旧matplotlib绘图中一样调用twinx()
.
Here's an example where you apply a custom mapping function to the dataframe of interest. Within the function, you can call plt.gca()
to get the current axis at the facet being currently plotted in FacetGrid. Once you have the axis, twinx()
can be called just like you would in plain old matplotlib plotting.
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
def facetgrid_two_axes(*args, **kwargs):
data = kwargs.pop('data')
dual_axis = kwargs.pop('dual_axis')
alpha = kwargs.pop('alpha', 0.2)
kwargs.pop('color')
ax = plt.gca()
if dual_axis:
ax2 = ax.twinx()
ax2.set_ylabel('Second Axis!')
ax.plot(data['x'],data['y1'], **kwargs, color='red',alpha=alpha)
if dual_axis:
ax2.plot(df['x'],df['y2'], **kwargs, color='blue',alpha=alpha)
df = pd.DataFrame()
df['x'] = np.arange(1,5,1)
df['y1'] = 1 / df['x']
df['y2'] = df['x'] * 100
df['facet'] = 'foo'
df2 = df.copy()
df2['facet'] = 'bar'
df3 = pd.concat([df,df2])
win_plot = sns.FacetGrid(df3, col='facet', size=6)
(win_plot.map_dataframe(facetgrid_two_axes, dual_axis=True)
.set_axis_labels("X", "First Y-axis"))
plt.show()
这不是最漂亮的图,因为您可能想调整第二个y轴标签的存在,图之间的间隔等,但是代码足以显示如何在FacetGrids中绘制两个不同幅度的系列
This isn't the prettiest plot as you might want to adjust the presence of the second y-axis' label, the spacing between plots, etc. but the code suffices to show how to plot two series of differing magnitudes within FacetGrids.
这篇关于在FacetGrid和双Y轴中结合 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!