简体   繁体   中英

Matplotlib bar chart: how to change names on axis x

I want to create a bar chart that will contain bars for 2 columns of dataframe.

from matplotlib import pyplot as plt
import pandas as pd

s = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
p_s = [0.05, 0.15, 0.20, 0.30, 0.20, 0.10]
p_s_x = [0.06005163309361129, 0.4378503494734475,0.3489460783665687,0.1404287057633398,0.012362455732360653,0.00036077757067209113]

df_to_plot = pd.DataFrame(data={"P(S)": p_s,
                                "P(S|X)": p_s_x,
                                "S": s})

df_to_plot.plot.bar(y=['P(S)', 'P(S|X)'],
                    alpha=0.7,
                    color=['red', 'green'],
                    figsize=(8,5))

This dataframe is here.

在此处输入图像描述 .

And bar chart I generate by

df_to_plot.plot.bar(y=['P(S)', 'P(S|X)'],
                   alpha=0.7,
                   color=['red', 'green'],
                   figsize=(8,5));

that looks

在此处输入图像描述

I want to replace 0,1,..., 5 into 0.1, ..., 0.6 (it's my column S), so I set x.

df_to_plot.plot.bar(y=['P(S)', 'P(S|X)'],
                    x='S',
                    alpha=0.7,
                    color=['red', 'green'],
                    figsize=(8,5));

which result is below. 在此处输入图像描述

I don't have any idea how to correct it. I used to use parameters use_index, xticks but they couldn't work.

Could you look at it and advise? Thank you!

Edit Thanks to @Mr.TI made a few changes.

ax = df_to_plot.plot.bar(y=['P(S)', 'P(S|X)'],
                         alpha=0.7,
                         color=['red', 'green'],
                         figsize=(8,5));
                         ax.set_xticklabels(df_to_plot['S'])

The chart looks fine now:) 在此处输入图像描述

I am writing an answer since I cannot write a comment due to the low reputation. Given your code, it creates an expected output with matplotlib version 3.3.4. Result image

from matplotlib import pyplot as plt
import pandas as pd


if __name__ == '__main__':
    s = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
    p_s = [0.05, 0.15, 0.20, 0.30, 0.20, 0.10]
    p_s_x = [0.06005163309361129, 0.4378503494734475,0.3489460783665687,0.1404287057633398,0.012362455732360653,0.00036077757067209113]
    
    df_to_plot = pd.DataFrame(data={"P(S)": p_s,
                                    "P(S|X)": p_s_x,
                                    "S": s})
    
    df_to_plot.plot.bar(y=['P(S)', 'P(S|X)'],
                    x='S',
                    alpha=0.7,
                    color=['red', 'green'],
                    figsize=(8,5))
    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