【问题标题】:Looping columns of data frame and plotting separately in Python循环数据框列并在 Python 中分别绘图
【发布时间】:2019-07-06 18:36:44
【问题描述】:

以下是我的代码片段。我想在折线图中一次绘制每一列与时间的关系。不同图中的每一列 但情节似乎不断在底部积累较旧的值。

import os
import pandas as pd
import numpy as np
from matplotlib import pyplot
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()


import re
def makeLinePlot(df):
    file_name="File Name not passed to this method"
    print("Ploting")
    df2=df
    fig,ax=plt.subplots(figsize=(30,8))
    i=0
    numRos = df.columns.size
    for colName in df.columns:
        i=i+1
        print(file_name,colName)
        df2[colName]=df2[colName].astype(float)
        print(colName,df2[colName].shape)
        g=sns.lineplot(x=df2.index, y=df2[colName], ax=ax)
        colNameR = re.sub('\W+','', colName )
        g.get_figure().savefig(colNameR+".png")


range = pd.date_range('2015-01-01', '2015-01-02', freq='1min')
df = pd.DataFrame(index = range)

# Average speed in miles per hour
df['speed'] = np.random.randint(low=0, high=60, size=len(df.index))
# Distance in miles (speed * 0.5 hours)
df['distance'] = df['speed'] * 0.25 
# Cumulative distance travelled
df['cumulative_distance'] = df.distance.cumsum()
makeLinePlot(df)

【问题讨论】:

  • 是的,由于ax=ax 两个线图都绘制到相同的轴上。因此,您需要创建两个图形,因此需要创建两个轴,然后您可以将每条线绘制到自己的 ax。
  • 如何解决它..
  • 循环内需要fig,ax = ...。

标签: python matplotlib seaborn


【解决方案1】:

我已经对您的代码进行了一些更改,现在看来我已经得到了您想要的。使用以下代码。

import os
import pandas as pd
import numpy as np
from matplotlib import pyplot
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()


import re
def makeLinePlot(df):
    df2=df
    i=0

    numRos = df.columns.size

    fig,ax =plt.subplots( nrows=1, ncols=numRos,figsize=(30,8))

    for index, colName in enumerate(df.columns):
        i=i+1
        df2[colName]=df2[colName].astype(float)
        print(colName,df2[colName].shape)
        g=sns.lineplot(x=df2.index, y=df2[colName], ax=ax[index])
        colNameR = re.sub('\W+','', colName )
        g.get_figure().savefig(colNameR+".png")


range = pd.date_range('2015-01-01', '2015-01-02', freq='1min')
df = pd.DataFrame(index = range)

# Average speed in miles per hour
df['speed'] = np.random.randint(low=0, high=60, size=len(df.index))
# Distance in miles (speed * 0.5 hours)
df['distance'] = df['speed'] * 0.25 
# Cumulative distance travelled
df['cumulative_distance'] = df.distance.cumsum()
makeLinePlot(df)

我有这个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多