0

I have as example the following DataFrame df and I want to plot the price as x-axis and share_1 and share_2 as y-axis in bar stacked form. I want to avoid using pandas.plot and rather using plt.bar and extract the x_values and y_values from the Dataframe.

Price size share_1  share_2
10    1     0.05     0.95
10    2     0.07     0.93
10    3     0.1      0.95
20    4     0.15     0.75
20    5     0.2.     0.8
20    6     0.35     0.65
30    7     0.5.     0.5
30    8     0.53     0.47
30    9     0.6.     0.4

This is the way I proceed:

x=  df['Price']
y1= df['share_1']
y2= df['share_2']
plt.bar(x,y1,label='share_1')
plt.bar(x,y2,label='share_2')

I still have the problem that the matplotlib removed the duplicate values the x-axis or maybe the mean value for the duplicated values is calculated automatically so that I get 3 value in the x-axis and not 6 as I aim to have. I don't know what is the reason.

my questions are:

  1. It's possible to extract x and y values as I did or should I convert the values in certain form as string or list?
  2. How can I avoid the fact that the duplicate values are removed in the x-axis. I want to have exactly the same number of x_values as in the DataFrame
jess
  • 81
  • 1
  • 7
  • 3
    Why don't you want pandas.plot? It uses matplotlib in the background anyway. – Quang Hoang Oct 25 '21 at 17:46
  • because it's possible to use fig, ax= plt.subplots() which I prefer than using pandas.plot – jess Oct 25 '21 at 17:54
  • 1
    You can pass `ax` to pandas plot too: `fig,ax = plt.subplots(); df.plot.bar(ax=ax)`. – Quang Hoang Oct 25 '21 at 17:55
  • 1
    @jess - I provided an answer with `plt.plot` as well as with `pandas.plot` specifying the axis to plot on. I would strongly recommend using the latter (i.e., `pandas`). – not_speshal Oct 25 '21 at 18:01
  • @QuangHoang I tried your code using fig, ax = plt.subplots() it did not work unfortunately, df.plot.bar(x="Price", y=["share_1","share_2"], stacked=True, ax=ax) did not work either! I'm wondering if the problem resides in Jupiter because I can find an explication why – jess Oct 25 '21 at 18:37

1 Answers1

0

Try:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.bar(x, y1, label="share_1")
ax.bar(x, y2, label="share_2", bottom=y1)
ax.set_xticks(x)
ax.legend()
ax.set_xticklabels(labels) 
plt.show()

enter image description here

As an aside, consider using pandas.plot as follows:

fig,ax = plt.subplots()
df.plot.bar(x="Price", y=["share_1","share_2"], stacked=True, ax=ax)
not_speshal
  • 22,093
  • 2
  • 15
  • 30