--- title: Virgil - EDA Visualization - S22 Extra Adding Text And Export Figure tags: Virgil, LearnWorld, EDAVisualization --- <a target="_blank" href="https://colab.research.google.com/drive/1vlQP9G8ZkUsEuIj8W3I5p7FYDHK4aBvC"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> # VISUALIZING WITH MATPLOTLIB AND PANDAS .plot() <img src="https://matplotlib.org/_static/logo2.png" alt="matplotlib" width="50%"/> ## 4. further reading ▸ ADDING TEXT ```plt.text( )``` ▸ https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.text.html Some important parameters: - `x`: x location - `y`: y location - `s`: message in string - `horizontalalignment` or `ha`: "center", "right", or "left" - `verticalalignment` or `va`: 'center', 'top', 'bottom', 'baseline', 'center_baseline' - Furthermore, any other formatting parameter can be passed in as a dictionary. Please refer in the link. ```python df = pd.read_csv('https://www.dropbox.com/s/ory0s3z89z3zkt4/restaurant.csv?dl=1') df.head() ``` ```python # Centerize the text plt.figure(figsize=(5, 5)) sns.countplot(data=df, x='day') plt.text(x=0, y=80, s="This is a string", ha='center', color='pink', fontsize='large') plt.show() ``` 🙋🏻‍♂️ **TASK: Find a way to put the value of each bar on top of the bar.** ```python plot_data = df.groupby('day').count()[['size']].loc[['Thur', 'Fri', 'Sat', 'Sun']] plot_data ``` ```python plt.figure(figsize=(8, 6)) sns.countplot(data=df, x='day', order = ['Thur', 'Fri', 'Sat', 'Sun']) for i in range(plot_data.shape[0]): plt.text(i, plot_data.values[i][0] + 1, plot_data.values[i][0], ha='center') plt.show() ``` ## 5. further reading ▸ EXPORT We can then use the `figure.Figure.savefig()` in order to save the figure to disk. Note that there are several useful flags we'll show below: * `transparent=True` makes the background of the saved figure transparent if the format supports it. * `dpi=80` controls the resolution (dots per square inch) of the output. * `bbox_inches="tight"` fits the bounds of the figure to our plot. Read more at: https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.savefig.html ```python # First you need to assign the figure into a variable fig = plt.figure(figsize=(5, 5)) sns.countplot(data=df, x='day') plt.show() ``` ```python # Save the figure fig.savefig('sales.png', transparent=False, dpi=80, bbox_inches="tight") ```