3

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.

1
  • pandas bar plots are categorical. Bars are at positions 0,1,2...N-1. You can use a matplotlib bar plot to get bars at numeric positions. Commented Jan 20, 2020 at 1:07

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

I would recommend using pandas.DataFrame.values instead of list(), the values attribute will give the content of the DataFrame as a numpy array

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.