【问题标题】:Setting xticklabels, x axis formatting in matplotlib在 matplotlib 中设置 xticklabels、x 轴格式
【发布时间】:2017-01-31 14:07:01
【问题描述】:

我想用每个条形中间点的图例值来格式化我的 x 轴,同时保留性别组标识。为了清楚起见,我想将性别组降低到其他 xticklabels 下方。

到目前为止,我已经添加了 xticks,但实际上正确且整齐地标记它们被证明是比较棘手的。

from itertools import chain, cycle
import logging
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
matplotlib.style.use("ggplot")


m = {"Males" :  {"Yes": 2, "No": 8}}
w = {"Females": {"Yes": 3, "No": 7}}
data = {**m, **w}
df = DataFrame(data)
# relative freq table
df_ft = (df / df.sum() * 100).T

ax = plt.subplot(111)
df_ft.plot(ax=ax, kind="bar", ylim=(0, 90),
           title="Would you prefer to work at home? (10 males, 10 females)",
           rot=0)
plt.ylabel("Relative Frequency (%)")


midp = 0.125  # standard bar width/2
t_l = ax.get_xticks().tolist()
ticks = list(chain.from_iterable((t - midp, t + midp) for t in t_l))
ax.set_xticks(t_l + ticks)

plt.show()

【问题讨论】:

    标签: matplotlib


    【解决方案1】:

    以下内容可能是您正在寻找的内容。

    from itertools import chain
    import matplotlib
    import matplotlib.pyplot as plt
    from pandas import DataFrame
    matplotlib.style.use("ggplot")
    
    
    df = DataFrame({'Males': {'Yes': 2, 'No': 8}, 'Females': {'Yes': 3, 'No': 7}})
    
    df_ft = (df / df.sum() * 100).T
    
    ax = plt.subplot(111)
    df_ft.plot(ax=ax, kind="bar", ylim=(0, 90),
               title="Would you prefer to work at home? (10 males, 10 females)",
               rot=0)
    plt.ylabel("Relative Frequency (%)")
    
    
    midp = 0.125  # standard bar width/2
    t_l = ax.get_xticks().tolist()
    ticks = list(chain.from_iterable((t - midp, t + midp) for t in t_l))
    ax.set_xticks(t_l + ticks)
    
    labels = [l for l in ax.get_xticklabels()]
    for i,l in enumerate(labels[len(df_ft):]):
        l.set_text(df_ft.columns[i % len(df_ft.columns)])
    for i,l in enumerate(labels[:len(df_ft)]):
        l.set_text("\n"+l.get_text())
    
    ax.set_xticklabels(labels)
    
    plt.savefig(__file__+".png")
    plt.show()
    

    【讨论】:

      【解决方案2】:

      Altair 会在这里做得很好。

      from altair import *
      from pandas import DataFrame
      
      
      df = DataFrame({'Males': {'Yes': 2, 'No': 8}, 'Females': {'Yes': 3, 'No': 7}})
      df = df.stack().reset_index()
      df.columns=['response','gender','count']
      

      可见 #1

      Chart(df).mark_bar().encode(x='gender',y='count',color='response').configure_cell(width=200, height=200)
      

      可见 2

      Chart(df).mark_bar().encode(x=X('response', axis=False),
                                  y=Y('count', axis=Axis(grid=False)),
                                  color='response',
                                  column=Column('gender', axis=Axis(axisWidth=1.0, offset=-8.0, orient='bottom'),scale=Scale(padding=30.0))).configure_cell(width=200, height=200).configure_facet_cell(strokeWidth=0)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-30
        • 1970-01-01
        • 2020-12-03
        • 1970-01-01
        • 2014-03-23
        • 2017-09-03
        • 2021-03-13
        相关资源
        最近更新 更多