第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

matplotlib 中是否可以有給定數(shù)量(n>2)的 y 軸?

matplotlib 中是否可以有給定數(shù)量(n>2)的 y 軸?

largeQ 2023-12-29 14:39:41
prices = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),                   columns=['a', 'b', 'c'])我有我的prices數(shù)據(jù)框,它目前有 3 列。但在其他時候,它可能有更多或更少的列。有沒有辦法使用某種twinx()循環(huán)來創(chuàng)建具有(可能)無限數(shù)量的 y 軸的所有不同時間序列的折線圖?我嘗試了下面的雙循環(huán),但我得到了typeError'd:bTypeError: 'AxesSubplot' object does not support item assignment# for i in range(0,len(prices.columns)):#     for column in list(prices.columns):#         fig, ax[i] = plt.subplots()#         ax[i].set_xlabel(prices.index()) #         ax[i].set_ylabel(column[i]) #         ax[i].plot(prices.Date, prices[column]) #         ax[i].tick_params(axis ='y') # #         ax[i+1] = ax[i].twinx() #         ax[i+1].set_ylabel(column[i+1]) #         ax[i+1].plot(prices.Date, column[i+1]) #         ax[i+1].tick_params(axis ='y') # #         fig.suptitle('matplotlib.pyplot.twinx() function \ Example\n\n', fontweight ="bold") #         plt.show() # =============================================================================我相信我明白為什么會收到錯誤 -ax對象不允許分配變量i。我希望有一些巧妙的方法來實現(xiàn)這一目標(biāo)。
查看完整描述

1 回答

?
慕運維8079593

TA貢獻(xiàn)1876條經(jīng)驗 獲得超5個贊

事實證明,主要問題是您不應(yīng)該將 pandas 繪圖函數(shù)與 matplotlib 混合使用,這會導(dǎo)致軸重復(fù)。否則,實現(xiàn)是相當(dāng)直接的,改編自這個matplotlib 示例

from mpl_toolkits.axes_grid1 import host_subplot

import mpl_toolkits.axisartist as AA

from matplotlib import pyplot as plt

from itertools import cycle

import pandas as pd



#fake data creation with different spread for different axes

#this entire block can be deleted if you import your df

from pandas._testing import rands_array

import numpy as np

fakencol=5

fakenrow=7

np.random.seed(20200916)

df = pd.DataFrame(np.random.randint(1, 10, fakenrow*fakencol).reshape(fakenrow, fakencol), columns=rands_array(2, fakencol))

df = df.multiply(np.power(np.asarray([10]), np.arange(fakencol)))

df.index = pd.date_range("20200916", periods=fakenrow)


#defining a color scheme with unique colors

#if you want to include more than 20 axes, well, what can I say

sc_color = cycle(plt.cm.tab20.colors)


#defining the size of the figure in relation to the number of dataframe columns

#might need adjustment for optimal data presentation

offset = 60

plt.rcParams['figure.figsize'] = 10+df.shape[1], 5


#host figure and first plot

host = host_subplot(111, axes_class=AA.Axes)

h, = host.plot(df.index, df.iloc[:, 0], c=next(sc_color), label=df.columns[0])

host.set_ylabel(df.columns[0])

host.axis["left"].label.set_color(h.get_color())

host.set_xlabel("time")


#plotting the rest of the axes

for i, cols in enumerate(df.columns[1:]):

  

    curr_ax = host.twinx()       


    new_fixed_axis = curr_ax.get_grid_helper().new_fixed_axis

    curr_ax.axis["right"] = new_fixed_axis(loc="right",

                                axes=curr_ax,

                                offset=(offset*i, 0))

    

    curr_p, = curr_ax.plot(df.index, df[cols], c=next(sc_color), label=cols)

    

    curr_ax.axis["right"].label.set_color(curr_p.get_color())

    curr_ax.set_ylabel(cols)

    curr_ax.yaxis.label.set_color(curr_p.get_color())



plt.legend()

plt.tight_layout()

plt.show()

https://img1.sycdn.imooc.com/658e69d50001ca0414940497.jpg

想想看 - 將軸平均分配到圖的左側(cè)和右側(cè)可能會更好。那好吧。



查看完整回答
反對 回復(fù) 2023-12-29
  • 1 回答
  • 0 關(guān)注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號