Skip to content

Bar plot of pandas Series requires first index value to be 0 #16387

Closed
@zeeMonkeez

Description

@zeeMonkeez

Bug report

Bug summary

When trying to plot a pandas Series with pyplot.bar(), it seems Series whose first index is not 0 cause a TypeError: only size-1 arrays can be converted to Python scalars exception when the bottom argument is given. When bottom is not given, bar width is not uniform as expected.

Code for reproduction

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'i':[1,4,4,4,6,6], 'n':[3,5,1,2,3,4]})

ix = df.index%2 == 0
plt.figure()
# produces expected plot with bars offset from x axis
plt.bar(x=df.loc[ix,'i'], height=df.loc[ix, 'n'], bottom=df.loc[ix, 'i'])
plt.figure()
# produces expected plot
plt.bar(x=df.loc[ix,'i'], height=df.loc[ix, 'n'])

ix = df.index%2 == 1
plt.figure()
# the following fails with `TypeError`
# plt.bar(x=df.loc[ix,'i'], height=df.loc[ix, 'n'], bottom=df.loc[ix, 'i'])

# converting to a list fixes the issue and produces the expected outcome.
# note that casting both x and bottom to list is required to produce expected outcome.
plt.bar(x=list(df.loc[ix,'i']), height=df.loc[ix, 'n'], bottom=list(df.loc[ix, 'i']))

plt.figure()
# produces plot with unexpected bar width
plt.bar(x=df.loc[ix,'i'], height=df.loc[ix, 'n'])

# again, converting to list produces expected outcome
plt.figure()
plt.bar(x=list(df.loc[ix,'i']), height=df.loc[ix, 'n'])

Matplotlib version

  • Operating system: macOS 10.15
  • Matplotlib version: 3.1.1
  • Matplotlib backend (print(matplotlib.get_backend())): MacOSX
  • Python version: 3.6.5
  • Jupyter version (if applicable):
  • Other libraries: pandas 0.25.2

Installed from conda, using default channel.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions