Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib plot line and bar chart together on same x-axis

When I plot two pandas dfs together as two line charts, I get them on the same x-axis properly. When I plot one as a bar chart, however, the axis seems to be offset.

ax = names_df.loc[:, name].plot(color='black')
living_df.loc[:, name].plot(figsize=(12, 8), ax=ax)

This works properly, producing this result

result

On the other hand, this:

ax = names_df.loc[:, name].plot(color='black')
living_df.loc[:, name].plot.bar(figsize=(12, 8), ax=ax)

does not, and has this result

result.

like image 440
j7_hi Avatar asked May 11 '26 21:05

j7_hi


1 Answers

Use matplotlib instead of calling the plot method of the pandas object:

import matplotlib.pyplot as plt

# Line plot
plt.plot(names_df.loc[:, name], color='black')
plt.plot(living_df.loc[:, name])
plt.show()
plt.close()

# Bar plot
plt.plot(names_df.loc[:, name].values)
bar_data = living_df.loc[:, name].values
plt.bar(range(len(bar_data)), bar_data)
plt.xticks(range(len(bar_data)), names_df.index.values)  # Restore xticks
plt.show()
plt.close()
like image 98
JafetGado Avatar answered May 13 '26 13:05

JafetGado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!