From ec266c1bd4ca08661f6fdbe249432a7148be5810 Mon Sep 17 00:00:00 2001 From: Simon Stone Date: Tue, 6 Jun 2023 10:13:30 -0400 Subject: [PATCH 1/2] make sure plot elements are not truncated --- episodes/09-plotting.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/episodes/09-plotting.md b/episodes/09-plotting.md index dbc74412e..8414b500c 100644 --- a/episodes/09-plotting.md +++ b/episodes/09-plotting.md @@ -348,14 +348,22 @@ matplotlib will make this variable refer to a new empty figure. Therefore, make sure you call `plt.savefig` before the plot is displayed to the screen, otherwise you may find a file with an empty plot. +Sometimes, some elements of the figure may get truncated when saving the figure to a file. You can find an in-depth explanation why this happens [here](https://matplotlib.org/stable/tutorials/intermediate/tight_layout_guide.html). To avoid this, we can call `plt.tight_layout` before `plt.savefig` to make sure that everything fits into the figure area. + +```python +plt.tight_layout() +plt.savefig('my_figure.png') +``` + When using dataframes, data is often generated and plotted to screen in one line. In addition to using `plt.savefig`, we can save a reference to the current figure -in a local variable (with `plt.gcf`) and call the `savefig` class method from +in a local variable (with `plt.gcf`) and call the `tight_layout` and `savefig` class method from that variable to save the figure to file. ```python data.plot(kind='bar') fig = plt.gcf() # get current figure +fig.tight_layout() fig.savefig('my_figure.png') ``` From 146c5652a02e210ae50351dd01b4c47773ebec74 Mon Sep 17 00:00:00 2001 From: Allen Lee Date: Sun, 17 Mar 2024 01:39:42 -0700 Subject: [PATCH 2/2] fix url --- episodes/09-plotting.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/episodes/09-plotting.md b/episodes/09-plotting.md index 8414b500c..bb373b474 100644 --- a/episodes/09-plotting.md +++ b/episodes/09-plotting.md @@ -348,7 +348,7 @@ matplotlib will make this variable refer to a new empty figure. Therefore, make sure you call `plt.savefig` before the plot is displayed to the screen, otherwise you may find a file with an empty plot. -Sometimes, some elements of the figure may get truncated when saving the figure to a file. You can find an in-depth explanation why this happens [here](https://matplotlib.org/stable/tutorials/intermediate/tight_layout_guide.html). To avoid this, we can call `plt.tight_layout` before `plt.savefig` to make sure that everything fits into the figure area. +Sometimes, some elements of the figure may get truncated when saving the figure to a file. You can find an in-depth explanation why this happens [here](https://matplotlib.org/stable/users/explain/axes/tight_layout_guide.html). To avoid this, we can call `plt.tight_layout` before `plt.savefig` to make sure that everything fits into the figure area. ```python plt.tight_layout()