2

I am generating plots like this one: enter image description here

When using less ticks, the plot fits nicely and the bars are wide enough to see them correctly. Nevertheless, when there are lots of ticks, instead of making the plot larger, it just compress the y axe, resulting in thin bars and overlapping tick text.

This is happening both for plt.show() and plt.save_fig().

Is there any solution so it plots the figure in a scale which guarantees that bars have the specified width, not more (if too few ticks) and not less (too many, overlapping)?

EDIT: Yes, I'm using barh, and yes, I'm setting height to a fixed value (8):

height = 8        
ax.barh(yvalues-width/2, xvalues, height=height, color='blue', align='center')
ax.barh(yvalues+width/2, xvalues, height=height, color='red', align='center')
Roman Rdgz
  • 12,836
  • 41
  • 131
  • 207
  • What commands are you using? `plt.barh`? Did you try adjusting the parameters specified in the manual http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.barh ... maybe `height` will help to force a bar width and scale the figure. If not, you'll probably have to compute the size by hand from your data (depending on max(data)-min(data) and min(np.diff(data)) – Ilja Mar 09 '17 at 11:08
  • @Ilja Yes, I'm using barh and setting height parameter. So, there is no way but manually computing the size? How shall I manually set the size? – Roman Rdgz Mar 09 '17 at 11:21

2 Answers2

0

I don't quite understand your code, it seems you do two plots with the same (only shifted) yvalues, but the image doesn't look so. And are you sure you want to shift by width/2 if you have align=center? Anyways, to changing the image size:

No, I am not sure there is no other way, but I don't see anything in the manual at a glance. To set image size by hand:

fig = plt.figure(figsize=(5, 80))
ax = fig.add_subplot(111)
...your_code

the size is in cm. You can compute it beforehand, try for example

import numpy as np
fig_height = (max(yvalues) - min(yvalues)) / np.diff(yvalue)

this would (approximately) set the minimum distance between ticks to a centimeter, which is too much, but try to adjust it.

Ilja
  • 2,024
  • 12
  • 28
0

I think of two solutions for your case:

  1. If you are trying to plot a histogram, use hist function [1]. This will automatically bin your data. You can even plot multiple overlapping histograms as long as you set alpha value lower than 1. See this post

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = mu + sigma*np.random.randn(10000)
    plt.hist(x, 50, normed=1, facecolor='green', 
             alpha=0.75,  orientation='horizontal')
    
  2. You can also identify interval of your axis ticks. This will place a tick every 10 items. But I doubt this will solve your problem.

    import matplotlib.ticker as ticker
    
    ...
    ax.yaxis.set_major_locator(ticker.MultipleLocator(10))
    
Hamdi
  • 931
  • 13
  • 31