Matplotlib sharex对具有不同x值的数据?

时间:2019-04-11 22:52:43

标签: python python-3.x pandas matplotlib seaborn

如何修改下面的代码,以使图跨所有6个x轴值,并且在df2的条形的A,C,F处只有空白点?

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame({'x':['A','B','C','D','E','F'],'y1':np.random.rand(6)})
df2 = pd.DataFrame({'x':['B','D','E'],'y2':np.random.rand(3)})

fig,axes = plt.subplots(2, sharex='all')

sns.barplot(x='x',y='y1',data=df,ax=axes[0])
sns.barplot(x='x',y='y2',data=df2,ax=axes[1])

enter image description here

2 个答案:

答案 0 :(得分:3)

仅使用matplotlib,就可以通过组合两个数据帧来实现:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

fig, axes = plt.subplots(2, sharex='all')

ax1, ax2 = axes

df = pd.DataFrame({'x': ['A', 'B', 'C', 'D', 'E', 'F'], 'y1': np.arange(6)})
df2 = pd.DataFrame({'x': ['B', 'D', 'E'], 'y2': np.random.rand(3)})

combined = df.merge(df2, how='left', on='x')

ax1.bar(combined['x'], combined['y1'])
ax2.bar(combined['x'], combined['y2'])

enter image description here

答案 1 :(得分:3)

Seaborn的galaxy_info: author: Jithendra description: blah...blah...blah min_ansible_version: 1.2 galaxy_tags:'[]' # List tags for your role here, one per line. A tag is # a keyword that describes and categorizes the role. # Users find roles by searching for tags. Be sure to # remove the '[]' above if you add tags to this list. # NOTE: A tag is limited to a single word comprised of # alphanumeric characters. Maximum 20 tags per role. dependencies: - { role: 'Master-role, when: blah == "true"'} #when condition is optional - { role: 'dependent1-role, when blah == "false"'} - { role: 'dependent2-role, when blah == "false"'} 参数可以采用一个列表,其中可以包含不在数据中的值。因此,您可以从x列中提供唯一值。

order

enter image description here