Reputation: 11155
I am writing a view in django which sends pdf file as a response. Pdf has a line graph of values against dates done using matplotlib.The graph looks very similar to this .
If i have the max y-data point as 1000, then the graph touches top x axis which i do not want.For example see this figure.
.
At (3.0,4.0) line graph touches top x-axis.
I want to give some extra space to yaxis(i.e increase max-y reading to 1100) so that my graph looks good, as shown in first image.
How would i do that?
from matplotlib.backends.backend_pdf import FigureCanvasPdf
from matplotlib.figure import Figure
from matplotlib.dates import DateFormatter
r_name = request.GET.get('r_name')
index_id = request.GET.get('index_id')
resp = api_views.historical_observations(request,index_id)
data = resp.data.get('data')
x,y=[],[]
for datam in data:
x.append(datam.get('measurement_date'))
y.append(datam.get('value'))
fig=Figure()
ax=fig.add_subplot(111)
ax.set_title(r_name)
ax.plot_date(x, y, '-bo')
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate()
canvas=FigureCanvasPdf(fig)
response= HttpResponse(content_type='application/pdf')
filename = settings.PDF_FILE_PREFIX+"_"+r_name+"_"+request.GET.get('start_date')+"_" +\
request.GET.get('end_date')+".pdf"
response['Content-Disposition'] = "attachment; filename="+filename
canvas.print_pdf(response)
return response
Upvotes: 4
Views: 3344
Reputation: 13539
Try either:
ax.set_ymargin(0.1)
(accepts float from 0 to 1)
or
ax.set_ylim([min(y)-1, max(Y)+1])
Change the 1 to something that makes the plot look good. It would depend on the scale of what you're plotting. For ylim you could do percentage adjustments by multiplying by 0.9 \ 1.1
Upvotes: 3