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.

student
  • 177
  • 2
  • 10
  • 2
    Does this answer your question? [How to plot a grouped bar plot from two or more dataframes](https://stackoverflow.com/q/58141058/7758804) – Trenton McKinney May 04 '23 at 18:25
  • 1
    Your plot is not correct. One plot overlaps the other. – Trenton McKinney May 04 '23 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)` – Trenton McKinney May 04 '23 at 18:31
  • I wanted to have df2 overlap on df1 if the ticker exists in df1, it's a lazy way to avoid making an extra column just to assign the bar colors. I'd have to merge the two dataframes, delete the overlapping tickers, then create a new column to assign different colors. I do not want to have two bars per ticker. – student May 04 '23 at 18:34
  • 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. – Quang Hoang May 04 '23 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](https://i.stack.imgur.com/MhE86.png) with sorted x-axis. – Trenton McKinney May 04 '23 at 18:47
  • @TrentonMcKinney well one thing I can say is that the values are always the same. – student May 04 '23 at 19:27

0 Answers0