0

This is my code:

import matplotlib.pyplot as plt
import pandas as pd

df1 = pd.DataFrame({
    'ticker': ['a', 'c', 'd', 'e', 'f', 'h'],
    'price': [1, 4, 5, 6, 8, 2]})

df2 = pd.DataFrame({
    'ticker': ['a', 'b', 'c', 'd', 'e'],
    'price': [1, 2, 4, 5, 6]})

df1.sort_values(by='price')
df2.sort_values(by='price')

plt.bar(df1['ticker'], df1['price'])
plt.bar(df2['ticker'], df2['price'])

the issue is that I'm not getting the right bar order: enter image description here

the bar order should be a-b-h-c-d-e-f.

7
  • 2
    Does this answer your question? How to plot a grouped bar plot from two or more dataframes Commented May 4, 2023 at 18:25
  • 1
    Your plot is not correct. One plot overlaps the other. Commented May 4, 2023 at 18:26
  • Create a single dataframe: df = pd.concat([d.assign(Set=i) for i, d in enumerate([df1, df2], 1)]), then pivot the dataframe dfp = df.pivot(index='ticker', columns='Set', values='price'), and then plot ax = dfp.plot(kind='bar', figsize=(8, 6), rot=0) Commented May 4, 2023 at 18:31
  • 2
    df1.sort_values(by='price') doesn't really do anything in your code. Plus, if you want to sort the values across the two dataframe, you would need to join/concat them anyway. Commented May 4, 2023 at 18:42
  • 2
    It's non-standard, and therefore probably confusing, to present to sets of data that way. Plotting multiple dataframes as "layered" bars can have unforeseen consequences, especially if the values in the two frames aren't the same. Additionally, using .assign easily adds the new column in the list comprehension. See code and plot with sorted x-axis. Commented May 4, 2023 at 18:47

0

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.