【问题标题】:Plot panda series in separate subplots using matplotlib使用 matplotlib 在单独的子图中绘制熊猫系列
【发布时间】:2015-04-04 16:56:24
【问题描述】:

希望得到一些帮助,我正在尝试使用 pandas 和 matplotlib 在单独的子图中绘制模拟数据,到目前为止我的代码是:

import matplotlib.pylab as plt
import pandas as pd
fig, ax = plt.subplots(2, 3)
for i in range(2):
    for j in range(50, 101, 10):
        for e in range(3):
            Var=(700* j)/ 100
            Names1 = ['ig','M_GZ']
            Data1 = pd.read_csv('~/File/JTL_'+str(Var)+'/GZ.csv', names=Names1)
            ig = Data1['ig']
            M_GZ=Data1['M_GZ']
            MGZ = Data1[Data1.M_GZ != 0]
            ax[i, e].plot(MGZ['ig'][:4], MGZ['M_GZ'][:4], '--v', linewidth=1.75)
plt.tight_layout()
plt.show()

但代码给了我 6 个相同情节的重复副本: 而不是Var 的每次迭代都有自己的情节,我尝试改变循环并使用不同的变体,例如:

fig = plt.figure()
for i in range(1, 7):
      ax = fig.add_subplot(2, 3, i)
            for j in range(50, 101, 10):                
                     Var=(700* j)/ 100
                     Names1 = ['ig','M_GZ']
                     Data1 = pd.read_csv('~/File/JTL_'+str(Var)+'/GZ.csv', names=Names1)
                     ig = Data1['ig']
                     M_GZ=Data1['M_GZ']
                     MGZ = Data1[Data1.M_GZ != 0]
                     ax.plot(MGZ['ig'][:4], MGZ['M_GZ'][:4], '--v', linewidth=1.75)
plt.tight_layout()
plt.show()

但这并没有改变我仍然得到与上面相同的情节。任何帮助将不胜感激,我希望每个子图都包含一组数据而不是全部六个

这是一个 Link 到 Dataframes 之一,每个子目录 ~/File/JTL_'+str(Var)+'/ 包含此文件的副本,总共有 6 个

【问题讨论】:

  • 你能展示一下Data1(数据框)的样子吗?
  • @user3645626 我添加了一个示例链接,说明其中一个数据框的外观是否足够,或者您认为所有 6 个数据框都会更有帮助?

标签: python matplotlib pandas plot subplot


【解决方案1】:

问题出在你的循环中

for i in range(2):  # Iterating rows of the plot
    for j in range(50, 101, 10): # Iterating your file names
        for e in range(3): # iterating the columns of the plot

最终结果是您迭代每个文件名

的所有列

对于这两项工作,您的循环中应该只有两个嵌套级别。潜在代码(更新):

import matplotlib.pylab as plt
import pandas as pd
fig, ax = plt.subplots(2, 3)
for row in range(2):
    for col in range(3):
        f_index = range(50, 101, 10)[row+1 * col]
        print row, col, f_index
        Var=(700* f_index)/ 100
        Names1 = ['ig','M_GZ']
        Data1 = pd.read_csv('~/File/JTL_'+str(Var)+'/GZ.csv', names=Names1)
        ig = Data1['ig']
        M_GZ=Data1['M_GZ']
        MGZ = Data1[Data1.M_GZ != 0]
        ax[row, col].plot(MGZ['ig'][:4], MGZ['M_GZ'][:4], '--v',linewidth=1.75)
plt.tight_layout()
plt.show()

【讨论】:

  • 我尝试了你的建议,但我一直收到IndexError: index 3 is out of bounds for axis 1 with size 3 但是当我将fig, ax 更改为fig, ax = plt.subplots(2, 6) 时,会生成一个图,其中顶行与底行完全相同,当添加print row, col 我得到0,0 0,1 0,2 0,3 而不是循环应该给出0,0 0,1 0,2 1,0 1,1 1,2
  • 哈哈,抱歉,我读得太快了,不知为何我以为只有 3 个文件。看看更新后的代码。
猜你喜欢
  • 2019-09-11
  • 1970-01-01
  • 1970-01-01
  • 2014-10-14
  • 1970-01-01
  • 2014-10-24
  • 1970-01-01
  • 2020-09-12
  • 2022-01-20
相关资源
最近更新 更多