Create Python Pandas Histograms For Specific Row Range As Well As Iterating Through Columns?
I have a set of data that I transpose to get the data groups into rows and have place holder values (for my case, series of mass values) in columns. My next goal is to draw histogr
Solution 1:
Here's a one basic approach,
df = pd.read_clipboard()
df = df.fillna(0)
print(df)
mz 902.4 909.4 915.3
0 n 0.6 0.3 1.4
1 n.1 0.4 0.3 1.3
2 n.2 0.3 0.2 1.1
3 n.3 0.2 0.2 1.3
4 n.4 0.4 0.3 1.4
5 DCIS 0.3 1.6 0.0
6 DCIS.1 0.3 1.2 0.0
7 DCIS.2 1.1 0.0 0.0
8 DCIS.3 0.2 1.2 0.0
9 DCIS.4 0.2 1.3 0.0
10 DCIS.5 0.2 0.1 1.5
11 br_1 0.5 0.4 1.4
12 br_1.1 0.2 1.3 0.0
13 br_1.2 0.5 0.2 1.4
14 br_1.3 0.5 0.2 1.6
15 br_1.4 1.4 0.0 0.0
Making the subsets (this step can be taken in to the iteration below if the logic can be well defined),
df_n = df.loc[df['mz'].str.startswith('n')]
df_D = df.loc[df['mz'].str.startswith('D')]
df_b = df.loc[df['mz'].str.startswith('b')]
Using matplotlib
's subplots()
import matplotlib.pyplot as plt
fig, ax = plt.subplots(nrows=df.shape[1]-1,ncols=1)
plt.tight_layout()
for i in range(1,df.shape[1]):
df_n.iloc[:,i].hist(ax=ax[i-1],color = 'k', alpha=0.4) # reduced alpha because you're plotting many histograms on top of each other
df_D.iloc[:,i].hist(ax=ax[i-1],color = 'r', alpha=0.4)
df_b.iloc[:,i].hist(ax=ax[i-1],color = 'orange', alpha=0.4)
ax[i-1].set_title("Histograms for " + df.columns[i])
Post a Comment for "Create Python Pandas Histograms For Specific Row Range As Well As Iterating Through Columns?"