簡體   English   中英

從列表中讀取標簽時,我不知道如何設置多行 xticklabels - matplotlib

[英]I can't figure out how to set multi-line xticklabels when reading labels from a list - matplotlib

正如標題所暗示的那樣,從兩個單獨的列表中讀取時,我無法找到有關如何將多行 xticklabels 打印到我的圖表上的任何文檔。 我聽說過關於如何制作一個單獨的不可見 x 軸然后設置第二行標簽的理論,但我還沒有看到任何代碼可以解釋如何做到這一點。 想法? 謝謝你的時間。

from inventoryClass import stockItem

import numpy as np
import matplotlib.pyplot as plt

def plotInventory(itemRecords) :

    stockBegin = []
    stockFinish = []  
    stockID = []   
    stockItems = []
    for rec in itemRecords.values() :
        stockBegin.append(rec.getStockStart())
        stockFinish.append(rec.getStockOnHand())
        stockID.append(rec.getID())
        stockItems.append(rec.getName())
    N = len(stockBegin)    
    tuple(stockBegin)
    tuple(stockFinish)

    ind = np.arange(N)  # the x locations for the groups
    width = 0.35       # the width of the bars

    fig, ax = plt.subplots()
    rects1 = ax.bar(ind, stockBegin, width, color='r')
    rects2 = ax.bar(ind + width, stockFinish, width, color='c')
    ymax = ax.get_ylim()    
    ax.set_ylim(0, (max(ymax) + 30))    



    # add some text for labels, title and axes ticks
    ax.set_ylabel('Inventory')
    ax.set_title('Stock start and end inventory, by item')
    ax.set_xticks(ind + width)
    ax.set_xticklabels(stockItems)
    ax.set_xticklabels(stockID)    
    ax.legend((rects1[0], rects2[0]), ('Start', 'End'))

    def autolabel(rects) :

        for rect in rects :
            height = rect.get_height()
            ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                    '%d' % int(height),
                ha='center', va='bottom')

    autolabel(rects1)
    autolabel(rects2)

plt.show()

我在這里嘗試完成的示例:

在此處輸入圖片說明

使用換行符連接您的兩個列表。 您可以將列表傳遞給ax.set

import matplotlib.pyplot as plt
xlab1 = [ "a", "b", "c"]
xlab2 = ["1", "2", "3"] 
xlabels = [f"{x1}\n{x2}" for x1, x2, in zip(xlab1,xlab2)]

fig, ax = plt.subplots()
_ = ax.bar([0, 3, 6], range(3), width=1)
_ = ax.bar([1, 4, 7], range(3), width=1)
_ = ax.set(xticks=[.5, 3.5, 6.5], xticklabels=xlabels)

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM