【问题标题】:Aligning/rotating text labels on x axis in matplotlib with 3 plots在 matplotlib 中用 3 个图对齐/旋转 x 轴上的文本标签
【发布时间】:2015-04-01 06:39:41
【问题描述】:

我应该如何将文本标签与图中的 x 行情对齐?我正在使用 host.set_xticklabels(labels,rotation='vertical') ,但这似乎不起作用。 我的标签是句子,有些可能比其他的更小/更大,例如“木乃伊归来第 2 部分”-如何在 x 轴下方填充一个空间以适应这个?

from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

path='/home/project/df.csv'
df=pd.read_csv(path,sep=',',header='infer')
xs =range(0,101)
ys =list(df['B'].ix[0:100])
zs=list(df['C'].ix[0:100])
ws=list(df['D'].ix[0:100])

if 1:
    host = host_subplot(111, axes_class=AA.Axes)
    p1, = host.plot(xs, ys, label='B')
    plt.subplots_adjust(right=0.75)

    par1 = host.twinx()
    par2 = host.twinx()

    offset = 60
    new_fixed_axis = par2.get_grid_helper().new_fixed_axis
    par2.axis["right"] = new_fixed_axis(loc="right",
                                        axes=par2,
                                        offset=(offset, 0))

    par2.axis["right"].toggle(all=True)
    host.set_xlim(min(xs), max(xs))
    host.set_ylim(100, max(ys))

    host.set_xlabel("A")
    host.set_ylabel("B")
    par1.set_ylabel("C")
    par2.set_ylabel("D")

    p2, = par1.plot(xs, ws, label='C',color='red')
    p3, = par2.plot(xs, zs, label='D',color='green')
    for tl in par1.get_yticklabels():
        tl.set_color('red')
    for tl in par2.get_yticklabels():
        tl.set_color('green')



    for tl in par1.get_yticklabels():
        tl.set_color('r')
    for tl in par2.get_yticklabels():
        tl.set_color('g')
    host.legend()

    host.axis["left"].label.set_color(p1.get_color())
    par1.axis["right"].label.set_color(p2.get_color())
    par2.axis["right"].label.set_color(p3.get_color())
    start, end, stepsize=0,len(df)-1,3
    host.xaxis.set_ticks(np.arange(start, end, stepsize))
    labels=list(df['A'])[0::stepsize]
    host.set_xticklabels(labels,rotation='vertical')
    plt.tight_layout()
    plt.draw()
    plt.show()

我需要对齐图中的“黑色”块。

我尝试了此处示例中的建议 python rotate values on xaxis to not overlap - plt.xticks(x, labels, rotation='vertical') 等,但没有奏效。

编辑 -: 从下面 Kazemakaze 的反馈中,这是我尝试过的 - : f,host=plt.subplots() #host = host_subplot(111, axes_class=AA.Axes) 但我也必须调整其余代码。你能提供一个双轴的例子吗?

我正在调整我的代码以适应 Secondary axis with twinx(): how to add to legend? 并且现在可以旋转,需要一些辅助轴上的指针。

【问题讨论】:

  • 在您的图片中很难看到 - 标签是否无法正确旋转?
  • 好吧,当我绘制它们时说标签[0:10] - 无论旋转如何,我都看到它们都在一条直线上 - 你可以用随机样本数据试试这个。我可以给你一个帖子编辑标签的文本。
  • 尝试使用示例标签 - [“木乃伊归来”、“lila”、“ringa ringa roses”、“多么美好的一天”]*10 [或任何随机数据中的记录数]
  • 我可以重现您的问题。似乎旋转不适用于host_subplot。使用plt.subplotinstead 时它可以正常工作。
  • @kazemakase 请具体一点,或者我可以测试然后接受它。还将我的编辑添加为上面的 cmets

标签: python matplotlib pandas


【解决方案1】:

这是我解决它的方法 - 不旋转的问题确实是 host_subplot 并且在使用 plt.subplot 时可以正常工作

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

path='/home/project/df.csv'
df=pd.read_csv(path,sep=',',header='infer')
xs =range(0,101)
ys =list(df['B'].ix[0:100])
zs=list(df['C'].ix[0:100])
ws=list(df['D'].ix[0:100])


def make_patch_spines_invisible(ax):
    ax.set_frame_on(True)
    ax.patch.set_visible(False)
    for sp in ax.spines.itervalues():
        sp.set_visible(False)


def three_way_plot(xs,ys,ws,zs,category):
    fig, host = plt.subplots()
    fig.subplots_adjust(right=0.6)
    par1 = host.twinx()
    par2 = host.twinx()
    par2.spines["right"].set_position(("axes", 1.1))
    p1, = host.plot(xs, ys, "blue", linewidth=2.0, label="B")
    p2, = par1.plot(xs, ws, "r-", label="C")
    p3, = par2.plot(xs, zs, "g-", label="D")
    host.set_xlim(min(xs), max(xs))
    host.set_ylim(min(ys), max(ys) + 200)
    par1.set_ylim(min(ws), max(ws) + 200)
    par2.set_ylim(min(zs), max(zs))
    host.set_xlabel("A", fontsize=14)
    host.set_ylabel("B", fontsize=14)
    par1.set_ylabel("C", fontsize=14)
    par2.set_ylabel("D", fontsize=14)
    host.yaxis.label.set_color(p1.get_color())
    par1.yaxis.label.set_color(p2.get_color())
    par2.yaxis.label.set_color(p3.get_color())
    lines = [p1, p2, p3]
    labels = ["mary had a little lamb","The mummy returns","Die another day","Welcome back"]*25
    start, end, step_size = 0, len(df) - 1, 4
    host.set_xticks(np.arange(start, end, step_size))
    host.set_xticklabels(labels, rotation='vertical', fontsize=10)
    host.legend(lines, [l.get_label() for l in lines])
    plt.tight_layout()
    plt.show()


three_way_plot(xs,ys,ws,zs,"category")

当然,我掩盖了数据的真实标签。

【讨论】:

    猜你喜欢
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 2020-12-04
    相关资源
    最近更新 更多