简体   繁体   中英

Plotting Pandas DataFrame with for Loop and Matplotlib?

I have a file that contains an unknown number of columns. The columns are a bunch of x and y values ordered in this fashion: x1, y1, x2, y2, x3, y3....etc. I want to plot them using a for loop as I want to integrate with it a colorbar were the colors are normalized against a variable written inside the code.

The code I wrote to load the txt file and name the columns as F1,F2,F3,...etc. So, my attempt to address switching between x and y, is through the modulo of the loop index. But it does not work:

import matplotlib.pyplot as plt
import pandas as pd

data = pd.read_csv('All.txt', delimiter='\t', header = None)
cols = list(data.columns.values)
index = 1
for column in cols:
    cols[index-1] = "F"+str(index)
    index += 1
vals = data.values.tolist()
newDataFrame = pd.DataFrame(vals,   columns=cols)

first_column = data[data.columns[0]]

for i in range(len(data.columns.values)):
    if i%2==1:
        plt.plot(data[data.columns[i]],data[data.columns[i+1]])
        index += 1
plt.show()

The code for colorbar is in this question: Matplotlib Logscale colorbar with for loop for loading data and plotting?

Summary: The problem have two parts: 1/ plotting the dataframe that contains x1,y1,x2,y2....etc. 2/ Integrating a colorbar with the loop.

Thanks !

1/ plotting the dataframe that contains x1,y1,x2,y2....etc.

When you plotting with Pandas DataFrame or Series, you should careful with index. I recommends you to transform data structure for looping like x, y array below example (I'm not sure what data do you want plotting..)

2/ Integrating a colorbar with the loop. Just modify code below. I hope you can change line color and change colorbar ticks

# Import Modules
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# Load Data
data = pd.read_csv('All.txt', delimiter='\t', header = None)

# Transform dataframe for looping
coordinates = [
    dict(
        x=data.values[:, (i*2)],
        y=data.values[:, (i*2)+1]
    )
    for i in range(len(data.columns)//2)
]

# Setup color bar
logs = np.logspace(3,7,10, endpoint=True)
norm = mpl.colors.Normalize(vmin=logs.min(), vmax=logs.max())
cmap = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.Reds)
cmap.set_array(logs)

# Plotting
fig = plt.figure()
for c in coordinates:

    plt.plot(c['x'], c['y'])
plt.colorbar(cmap, ticks=logs)

plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM