2

Considers the simple data frame below:

import pandas  as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'var3':[1,3,9,6,1,6,3,1,1,3],
                   'var1':[9,1,2,6,6,5,9,3,1,7],
                   'var2':[6,6,2,9,8,3,5,4,1,3]})
df

enter image description here

Now, let's plot a set of histograms from this data:

df.hist(layout=(1,3))
plt.show()

enter image description here

Note that the order (from left to right) of the histograms in the figure is different from the order of the columns in the data frame. How to make the histograms obey the order of its data source?

2 Answers 2

1

I could not find a way to do that within the df.hist() function. But you can accomplish it with the simple loop below:

fig, ax = plt.subplots(1, len(df.columns), figsize=(3*len(df.columns), 3))
for i, var in enumerate(df):
    df[var].hist(ax=ax[i])
    ax[i].set_title(var)
plt.show()

Result:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

I like @foglerit's answer, but here's another workaround solution:

import pandas  as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'var3':[1,3,9,6,1,6,3,1,1,3],
                   'var1':[9,1,2,6,6,5,9,3,1,7],
                   'var2':[6,6,2,9,8,3,5,4,1,3]})

columns = df.columns  # save original column names
columns_temp = []  # create temporary column names, numbered
for i, col in enumerate(df.columns):
    columns_temp.append('(' + str(i+1) + ') ' + str(col))
df.columns = columns_temp

df.hist(layout=(1,3))  # now the column order is not messed up

df.columns = columns  # reassign original column names

df.hist plot

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.