Home > Enterprise >  How to make the x-axis of a histogram (df.hist) finer (more values within a given space)
How to make the x-axis of a histogram (df.hist) finer (more values within a given space)

Time:11-22

I have the following code. I am looping through variables (dataframe columns) and create histograms. I have attached below an example of a graph for the column newerdf['distance'].

I would like to increase the number of values on the x-axis, so that the x-axis values on the graph below say 0,1,2,3,4,5,6,7,8,9,10 rather than 0,5,10.

I would be so grateful for a helping hand!

listedvariables = ['distance','duration','sleepiness_bed','sleepiness_waking','normal_time_of_wakeup','number_of_times_wakeup_during_night','time_spent_awake_during_night_mins','time_of_going_to_sleep','time_to_fall_asleep_mins','sleep_onset_time','sleep_period_length_mins','total_sleep_duration_mins','time_in_bed_mins','sleep_efficiency','sleep_bout_length_mins','mid_point_of_sleep','sleepiness_resolution_index']
for i in range(0,len(listedvariables)): 
    fig = newerdf[[listedvariables[i]]].hist(figsize=(30,20))
    [x.title.set_size(40) for x in fig.ravel()]
    [x.tick_params(axis='x',labelsize=40) for x in fig.ravel()]
    [x.tick_params(axis='y',labelsize=40) for x in fig.ravel()]
    plt.tight_layout()

enter image description here

CodePudding user response:

With the following toy dataframe and plot in a Jupyter notebook:

import pandas as pd
from matplotlib import pyplot as plt

df = pd.DataFrame(
    {
        "A": [
            1.5660150383101321,
            0.3145564820111119,
            0.36639603868848436,
            1.0212995716690398,
            0.3956186117590027,
            1.5621280556024015,
            1.3832769133918796,
            0.5007889864878086,
            0.4756689950693606,
            0.9305468188471707,
        ]
    }
)
plt.hist(df["A"])

output

enter image description here

To add more ticks and labels:

plt.xticks(
    ticks=[
        0.0,
        0.1,
        0.2,
        0.3,
        0.4,
        0.5,
        0.6,
        0.7,
        0.8,
        0.9,
        1.0,
        1.1,
        1.2,
        1.3,
        1.4,
        1.5,
        1.6,
    ],
)
plt.hist(df["A"])

output

enter image description here

  • Related