Getting an Image Size error in Guided Project: Storytelling Data Visualization on Exchange Rates

Screen Link:

My Code:

### Adding the FiveThirtyEight style
import matplotlib.style as style
style.use('fivethirtyeight')

### Adding the plot
fig,ax = plt.subplots(figsize=(8,3))


ax.plot(financial_crisis['Time'],
        financial_crisis['rolling_mean'],
        linewidth=1, color='#A6D785')

### Highlighting the 2007-2008 period
ax.plot(financial_crisis_7_8['Time'],
        financial_crisis_7_8['rolling_mean'],
        linewidth=3, color='#e23d28')

### Highlihting the peak of the crisis
# ax.axvspan(xmin=13950, xmax=14140, ymin=0.09,
#            alpha=0.3, color='grey')

xmin = pd.to_datetime("2008-04", format = "%Y-%m")
xmax = pd.to_datetime("2008-09", format = "%Y-%m")

ax.axvspan(xmin=xmin,xmax=xmax, ymin=0.09,alpha=0.3, color='grey')

### Adding separate tick labels
ax.set_xticklabels([])
ax.set_yticklabels([])

x = 13110
for year in ['2006', '2007', '2008', '2009', '2010']:
    ax.text(x, 1.13, year, alpha=0.5, fontsize=11)
    x += 365

y = 1.193   
for rate in ['1.2', '1.3', '1.4', '1.5']:
    ax.text(13020, y, rate, alpha=0.5, fontsize=11)
    y += 0.1

### Adding a title and a subtitle    
ax.text(13020, 1.67, "Euro-USD rate peaked at 1.59 during 2007-2008's financial crisis",
        weight='bold')
ax.text(13020, 1.63, 'Euro-USD exchange rates between 2006 and 2010',
        size=12)

### Adding a signature
ax.text(13, 1.07, '©DATAQUEST' + ' '*94 + 'Source: European Central Bank',
        color = '#f0f0f0', backgroundcolor = '#4d4d4d',
        size=10)

### Add some transparency to the grid
ax.grid(alpha=0.5)

plt.show()

I want the graph to display but I am getting an image size error.

Could someone please address how to adjust the image pixel to display the graph. I am getting following error;
ValueError: Image size of 229148x271 pixels is too large. It must be less than 2^16 in each direction.

Whole error is available below
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\formatters.py in __call__(self, obj)
    339                 pass
    340             else:
--> 341                 return printer(obj)
    342             # Finally look for special method names
    343             method = get_real_method(obj, self.print_method)

C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in <lambda>(fig)
    246 
    247     if 'png' in formats:
--> 248         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    249     if 'retina' in formats or 'png2x' in formats:
    250         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
    130         FigureCanvasBase(fig)
    131 
--> 132     fig.canvas.print_figure(bytes_io, **kw)
    133     data = bytes_io.getvalue()
    134     if fmt == 'svg':

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, **kwargs)
   2089                     orientation=orientation,
   2090                     bbox_inches_restore=_bbox_inches_restore,
-> 2091                     **kwargs)
   2092             finally:
   2093                 if bbox_inches and restore_bbox:

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in print_png(self, filename_or_obj, metadata, pil_kwargs, *args, **kwargs)
    525 
    526         else:
--> 527             FigureCanvasAgg.draw(self)
    528             renderer = self.get_renderer()
    529             with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self)
    384         Draw the figure using the renderer.
    385         """
--> 386         self.renderer = self.get_renderer(cleared=True)
    387         with RendererAgg.lock:
    388             self.figure.draw(self.renderer)

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in get_renderer(self, cleared)
    397                           and getattr(self, "_lastKey", None) == key)
    398         if not reuse_renderer:
--> 399             self.renderer = RendererAgg(w, h, self.figure.dpi)
    400             self._lastKey = key
    401         elif cleared:

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in __init__(self, width, height, dpi)
     84         self.width = width
     85         self.height = height
---> 86         self._renderer = _RendererAgg(int(width), int(height), dpi)
     87         self._filter_renderers = []
     88 

ValueError: Image size of 229148x271 pixels is too large. It must be less than 2^16 in each direction.

<Figure size 576x216 with 1 Axes>
1 Like

Hi @ali_acma, the problem here is that the coordinates you’re using are too far from the actual coordinates, which makes the image too big, hence the error message:

Image size of 229148x271 pixels is too large.

Unfortunately, the x-coordinates (behind the datetime units) are not fixed in matplotlib (to fix them, you’d need a slightly more complicated coding approach), so the solution here is to use ax.get_xticks() and ax.get_yticks() to see what are the coordinates and then adjust your input coordinates accordingly.

2 Likes

Thank you so much. My problem has been resolved

1 Like

Hello @alex, after using ax.get_xticks() and ax.get_yticks() to see what are the coordinates, what should we do next? Use ax.set_xticks()?
If yes, where in the code? Because i tried it and still getting the same error.

Thanks,

Hamid

1 Like

Hi, @hamidfagbemi, you should use ax.get_xticks() and ax.get_yticks() only temporary to see what are the x- and y-coordinates. After that, you can remove these two methods from your code.

Essentially, you first find out what are the coordinates, and then you start making use of that. In the project, for the first graph, you’d need to use ax.get_xticks() and ax.get_yticks() before this code (because you’ll need the coordinates for ax.axvspan()).

### Highlihting the peak of the crisis
ax.axvspan(xmin=13950, xmax=14140, ymin=0.09,
           alpha=0.3, color='grey')

Let me know if this clarifies things for you.

Hello @alex, I m doing the second graph. I used ax1.get_xticks() and ax1.get_yticks() at the very end of the code lines. I got some coordinates. I tried to used them with ax1.set_xticks(coordinates) but still did not work. Do you know where i was wrong?

Thanks,

Hamid

Hello @alex,
I am also confused about this explanation.
For example, when I tried to print this one to see the x-coordinate:
print(ax.get_xticks())
it shows:
array([732312., 732493., 732677., 732858., 733042., 733224., 733408.,
733589., 733773.])

So, what the number I should use? I haven’t figure out why in the solution shows using number “13110” when create x-ticklabel (assume that I will create highlight period later when I understand this concept:

x = 13110
for year in [‘2006’, ‘2007’, ‘2008’, ‘2009’, ‘2010’]:
ax.text(x, 1.13, year, alpha=0.5, fontsize=11)
x += 365

Many thanks!

1 Like