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

5
  • 2
    Question and task is unclear. And please do post your code whatever you're trying. Commented Dec 14, 2019 at 7: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:machinelearningplus.com/plots/… (section ordered bar chart) Commented Dec 14, 2019 at 8:09
  • 1
    Does this answer your question? How to draw axis in the middle of the figure? Commented Dec 14, 2019 at 12:23
  • @Eddie11: Please add some test code that demonstrates the type of data and the exact plotting function you want to use. Commented Dec 14, 2019 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. Commented Dec 16, 2019 at 23:33

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

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.