2

How to plot not only values but also the labels on an axis with matplotlib with a dict like this:

D = {'label1': 7.33, 'label2': 7.12, 'label3': 4.26, 'label4': 6.98}

?

it should output

enter image description here

This goal is to see the outliers very easily graphically, i.e. a 1D-scatter plot, like this:

enter image description here

but with a label near each point.

Basj
  • 41,386
  • 99
  • 383
  • 673
  • Thew optimal strategy depends on what kind of data you show (i.e. whether each data point gets its own label or not). The question does not provide enough detail to find out though. – ImportanceOfBeingErnest Sep 07 '18 at 15:46
  • @ImportanceOfBeingErnest Yes, each data point (~ 20 points) gets its own label. – Basj Sep 07 '18 at 15:50

1 Answers1

1

You could use the minor and major ticklabels to alternate between showing the label above and below the axis.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

D = {'label1': 7.33, 'label2': 7.12, 'label3': 4.26, 'label4': 6.98}

labs, vals = zip(*sorted([(k,v) for k,v in D.items()], key=lambda t: t[1] ))
ticks = ["{}\n{}".format(k,v) for k,v in zip(labs,vals)]

ax.set_xticks(vals[::2])
ax.set_xticklabels(ticks[::2])
ax.set_xticks(vals[1::2], minor=True)
ax.set_xticklabels(ticks[1::2], minor=True, va="bottom")

ax.tick_params(which="minor", direction="in", pad=-10 )


plt.plot(vals, list(range(len(vals))))
plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Thank you! How to plot the horizontal axis only, and no y-axis, no curve, no boundary rectangle etc.? i.e. just like the example image in the question – Basj Sep 07 '18 at 16:38
  • See https://stackoverflow.com/questions/925024/how-can-i-remove-the-top-and-right-axis-in-matplotlib – ImportanceOfBeingErnest Sep 07 '18 at 16:42
  • This removes the boundary box, but the y-axis is still there, how to have an horizontal axis only? Something like this but with labels for each point: https://commons.wikimedia.org/wiki/File:R-US_state_areas-1D_jitter.svg – Basj Sep 07 '18 at 17:09
  • See https://stackoverflow.com/questions/12998430/remove-xticks-in-a-matplotlib-plot – ImportanceOfBeingErnest Sep 07 '18 at 17:11
  • It seems that [`scatter`](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html) is a more natural way to do it (i.e. no need to create a 2D graphic and then manually remove the box, remove the y-axis, etc.) – Basj Sep 07 '18 at 18:39