Stuck with Image size issue - Guided Project: Storytelling Data Visualization on Exchange Rates

Screen Link: https://app.dataquest.io/m/529/guided-project%3A-storytelling-data-visualization-on-exchange-rates/6/coding-the-graph

I tried to run the following code code from the solution notebook.

### 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')

### 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(13020, 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()

The following error message popped up.

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-11-c83a3844850c> in <module>
     19 
     20 ### Adding separate tick labels
---> 21 ax.set_xticklabels([])
     22 ax.set_yticklabels([])
     23 

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/axes/_base.py in set_xticklabels(self, labels, fontdict, minor, **kwargs)
   3386         if fontdict is not None:
   3387             kwargs.update(fontdict)
-> 3388         ret = self.xaxis.set_ticklabels(labels,
   3389                                         minor=minor, **kwargs)
   3390         self.stale = True

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/axis.py in set_ticklabels(self, ticklabels, minor, *args, **kwargs)
   1730         else:
   1731             self.set_major_formatter(mticker.FixedFormatter(ticklabels))
-> 1732             ticks = self.get_major_ticks()
   1733         ret = []
   1734         for tick_label, tick in zip(ticklabels, ticks):

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/axis.py in get_major_ticks(self, numticks)
   1429         'Get the tick instances; grow as necessary.'
   1430         if numticks is None:
-> 1431             numticks = len(self.get_majorticklocs())
   1432 
   1433         while len(self.majorTicks) < numticks:

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/axis.py in get_majorticklocs(self)
   1346     def get_majorticklocs(self):
   1347         """Get the array of major tick locations in data coordinates."""
-> 1348         return self.major.locator()
   1349 
   1350     def get_minorticklocs(self):

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/dates.py in __call__(self)
   1336     def __call__(self):
   1337         'Return the locations of the ticks'
-> 1338         self.refresh()
   1339         return self._locator()
   1340 

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/dates.py in refresh(self)
   1362     def refresh(self):
   1363         # docstring inherited
-> 1364         dmin, dmax = self.viewlim_to_dt()
   1365         self._locator = self.get_locator(dmin, dmax)
   1366 

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/dates.py in viewlim_to_dt(self)
   1092             vmin, vmax = vmax, vmin
   1093         if vmin < 1:
-> 1094             raise ValueError('view limit minimum {} is less than 1 and '
   1095                              'is an invalid Matplotlib date value. This '
   1096                              'often happens if you pass a non-datetime '

ValueError: view limit minimum -22041.1 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units

Error in callback <function install_repl_displayhook.<locals>.post_execute at 0x7fb1a5906c10> (for post_execute):
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/pyplot.py in post_execute()
    107             def post_execute():
    108                 if matplotlib.is_interactive():
--> 109                     draw_all()
    110 
    111             # IPython >= 2

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/_pylab_helpers.py in draw_all(cls, force)
    125         for f_mgr in cls.get_all_fig_managers():
    126             if force or f_mgr.canvas.figure.stale:
--> 127                 f_mgr.canvas.draw_idle()
    128 
    129 atexit.register(Gcf.destroy_all)

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/backend_bases.py in draw_idle(self, *args, **kwargs)
   1945         if not self._is_idle_drawing:
   1946             with self._idle_draw_cntx():
-> 1947                 self.draw(*args, **kwargs)
   1948 
   1949     @cbook.deprecated("3.2")

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py in draw(self)
    391              (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar
    392               else nullcontext()):
--> 393             self.figure.draw(self.renderer)
    394             # A GUI class may be need to update a window using this draw, so
    395             # don't forget to call the superclass.

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     36                 renderer.start_filter()
     37 
---> 38             return draw(artist, renderer, *args, **kwargs)
     39         finally:
     40             if artist.get_agg_filter() is not None:

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/figure.py in draw(self, renderer)
   1733 
   1734             self.patch.draw(renderer)
-> 1735             mimage._draw_list_compositing_images(
   1736                 renderer, self, artists, self.suppressComposite)
   1737 

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    135     if not_composite or not has_images:
    136         for a in artists:
--> 137             a.draw(renderer)
    138     else:
    139         # Composite any adjacent images together

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     36                 renderer.start_filter()
     37 
---> 38             return draw(artist, renderer, *args, **kwargs)
     39         finally:
     40             if artist.get_agg_filter() is not None:

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
   2628             renderer.stop_rasterizing()
   2629 
-> 2630         mimage._draw_list_compositing_images(renderer, self, artists)
   2631 
   2632         renderer.close_group('axes')

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    135     if not_composite or not has_images:
    136         for a in artists:
--> 137             a.draw(renderer)
    138     else:
    139         # Composite any adjacent images together

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     36                 renderer.start_filter()
     37 
---> 38             return draw(artist, renderer, *args, **kwargs)
     39         finally:
     40             if artist.get_agg_filter() is not None:

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)
   1225         renderer.open_group(__name__, gid=self.get_gid())
   1226 
-> 1227         ticks_to_draw = self._update_ticks()
   1228         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
   1229                                                                 renderer)

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/axis.py in _update_ticks(self)
   1101         the axes.  Return the list of ticks that will be drawn.
   1102         """
-> 1103         major_locs = self.get_majorticklocs()
   1104         major_labels = self.major.formatter.format_ticks(major_locs)
   1105         major_ticks = self.get_major_ticks(len(major_locs))

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/axis.py in get_majorticklocs(self)
   1346     def get_majorticklocs(self):
   1347         """Get the array of major tick locations in data coordinates."""
-> 1348         return self.major.locator()
   1349 
   1350     def get_minorticklocs(self):

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/dates.py in __call__(self)
   1336     def __call__(self):
   1337         'Return the locations of the ticks'
-> 1338         self.refresh()
   1339         return self._locator()
   1340 

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/dates.py in refresh(self)
   1362     def refresh(self):
   1363         # docstring inherited
-> 1364         dmin, dmax = self.viewlim_to_dt()
   1365         self._locator = self.get_locator(dmin, dmax)
   1366 

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/dates.py in viewlim_to_dt(self)
   1092             vmin, vmax = vmax, vmin
   1093         if vmin < 1:
-> 1094             raise ValueError('view limit minimum {} is less than 1 and '
   1095                              'is an invalid Matplotlib date value. This '
   1096                              'often happens if you pass a non-datetime '

ValueError: view limit minimum -22041.1 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/dataquest/system/env/python3/lib/python3.8/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)

/dataquest/system/env/python3/lib/python3.8/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))

/dataquest/system/env/python3/lib/python3.8/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':

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, **kwargs)
   2098                            else suppress())
   2099                     with ctx:
-> 2100                         self.figure.draw(renderer)
   2101                     bbox_artists = kwargs.pop("bbox_extra_artists", None)
   2102                     bbox_inches = self.figure.get_tightbbox(renderer,

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     36                 renderer.start_filter()
     37 
---> 38             return draw(artist, renderer, *args, **kwargs)
     39         finally:
     40             if artist.get_agg_filter() is not None:

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/figure.py in draw(self, renderer)
   1733 
   1734             self.patch.draw(renderer)
-> 1735             mimage._draw_list_compositing_images(
   1736                 renderer, self, artists, self.suppressComposite)
   1737 

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    135     if not_composite or not has_images:
    136         for a in artists:
--> 137             a.draw(renderer)
    138     else:
    139         # Composite any adjacent images together

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     36                 renderer.start_filter()
     37 
---> 38             return draw(artist, renderer, *args, **kwargs)
     39         finally:
     40             if artist.get_agg_filter() is not None:

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
   2628             renderer.stop_rasterizing()
   2629 
-> 2630         mimage._draw_list_compositing_images(renderer, self, artists)
   2631 
   2632         renderer.close_group('axes')

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    135     if not_composite or not has_images:
    136         for a in artists:
--> 137             a.draw(renderer)
    138     else:
    139         # Composite any adjacent images together

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     36                 renderer.start_filter()
     37 
---> 38             return draw(artist, renderer, *args, **kwargs)
     39         finally:
     40             if artist.get_agg_filter() is not None:

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)
   1225         renderer.open_group(__name__, gid=self.get_gid())
   1226 
-> 1227         ticks_to_draw = self._update_ticks()
   1228         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
   1229                                                                 renderer)

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/axis.py in _update_ticks(self)
   1101         the axes.  Return the list of ticks that will be drawn.
   1102         """
-> 1103         major_locs = self.get_majorticklocs()
   1104         major_labels = self.major.formatter.format_ticks(major_locs)
   1105         major_ticks = self.get_major_ticks(len(major_locs))

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/axis.py in get_majorticklocs(self)
   1346     def get_majorticklocs(self):
   1347         """Get the array of major tick locations in data coordinates."""
-> 1348         return self.major.locator()
   1349 
   1350     def get_minorticklocs(self):

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/dates.py in __call__(self)
   1336     def __call__(self):
   1337         'Return the locations of the ticks'
-> 1338         self.refresh()
   1339         return self._locator()
   1340 

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/dates.py in refresh(self)
   1362     def refresh(self):
   1363         # docstring inherited
-> 1364         dmin, dmax = self.viewlim_to_dt()
   1365         self._locator = self.get_locator(dmin, dmax)
   1366 

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/dates.py in viewlim_to_dt(self)
   1092             vmin, vmax = vmax, vmin
   1093         if vmin < 1:
-> 1094             raise ValueError('view limit minimum {} is less than 1 and '
   1095                              'is an invalid Matplotlib date value. This '
   1096                              'often happens if you pass a non-datetime '

ValueError: view limit minimum -22041.1 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units

<Figure size 1000x600 with 1 Axes>

When I used the following code

print(ax.get_xticks())
print(ax.get_yticks())

I got this output.

[732312. 732493. 732677. 732858. 733042. 733224. 733408. 733589. 733773.]
[1.1 1.2 1.3 1.4 1.5 1.6]

What should I do with these x - coordinates figures?
It’s very confusing how to figure the right value for the xmin and xmax values.

1 Like

Hi,

ax.get_xticks() gives you the coordinates of the xticks. So if you want to replace the labels and set them with your own labels, you can use the output of ax.get_xticks().

In this exercise, I used it like this:

ax_bush.set_xticks(ax_bush.get_xticks())
ax_bush.set_xticklabels([’’, β€˜2001’, β€˜β€™, β€˜2003’, β€˜β€™, β€˜2005’, β€˜β€™, β€˜2007’, β€˜β€™, β€˜2009’], alpha=0.3)

With this code, the ax gets the correct amount of ticks, the right coordinates for the xlabels and in set_xticklabels it gets every other year.

I hope this helps.