1

I'd like to set my tick labels along the zero axis but have the labels placed at the bottom of the plot (similar to the example plot). Simple to do in Excel, but I've been unable to find a solution here for matplotlib. I'm new to matplotlib, so sorry if this is obvious, but have been searching for a couple hours and can't figure it out.

The following test code creates a plot, but without ticks on the x-axis at y=0 :

from matplotlib import pyplot as plt
import pandas as pd

df = pd.DataFrame({'x': ["NegFour", "NegThree", "NegTwo", "NegOne", "One", "Two", "Three", "Four"],
                   'y': [-4, -3, -2, -1, 1, 2, 3, 4]})
plt.figure()
plt.bar(x=df['x'], height=df['y'], width=.3)
plt.show()

Desired output:

example plot

JohanC
  • 71,591
  • 8
  • 33
  • 66
Eddie11
  • 13
  • 4
  • 2
    Question and task is unclear. And please do post your code whatever you're trying. – theashwanisingla Dec 14 '19 at 07:13
  • 1
    `plt.xticks(df.index, df[1].str.upper(), rotation=60, horizontalalignment='right')` might be what you are looking for. Especially the rotation argument. Example is here:https://www.machinelearningplus.com/plots/top-50-matplotlib-visualizations-the-master-plots-python/ (section ordered bar chart) – Kolibril Dec 14 '19 at 08:09
  • 1
    Does this answer your question? [How to draw axis in the middle of the figure?](https://stackoverflow.com/questions/31556446/how-to-draw-axis-in-the-middle-of-the-figure) – Diziet Asahi Dec 14 '19 at 12:23
  • @Eddie11: Please add some test code that demonstrates the type of data and the exact plotting function you want to use. – JohanC Dec 14 '19 at 15:46
  • @DizietAsahi, I don't think that answer shows how to display the ticks in the middle and the labels at the bottom. – Don Kirkby Dec 16 '19 at 23:33

1 Answers1

0

The trick is to draw the ticks on the top axis, and the labels on the bottom axis, then put the top axis at the zero point. Axes.tick_params() seems to have the most important options.

from matplotlib import pyplot as plt
import pandas as pd

df = pd.DataFrame({'x': ["NegFour", "NegThree", "NegTwo", "NegOne", "One", "Two", "Three", "Four"],
                   'y': [-4, -3, -2, -1, 1, 2, 3, 4]})
fig = plt.figure()
plt.bar(x=df['x'], height=df['y'], width=.3)

ax = plt.gca()
# Put top x axis at zero
ax.spines['top'].set_position('zero')
# Don't draw lines for bottom and right axes.
ax.spines['bottom'].set_color('none')
ax.spines['right'].set_color('none')
# Draw ticks on top x axis, and leave labels on bottom.
ax.tick_params(axis='x', bottom=False, top=True, direction='inout')

plt.show()

Here's the result:

example plot

Don Kirkby
  • 53,582
  • 27
  • 205
  • 286