Nagendra18/Matplotlib-Seaborn
0
1import streamlit as st2import matplotlib.pyplot as plt3import numpy as np4import pandas as pd5 6 7st.title(":blue[Understanding subplot2grid]")8st.markdown("<hr style='border: 2px dotted green;'>", unsafe_allow_html=True)9 10 11st.write("""12`subplot2grid` is a function in Matplotlib used to create subplots in a more flexible grid layout. It allows you to specify the grid size and the position of each subplot, giving you more control over complex plot arrangements compared to the `plt.subplot()` function.13 14### Key Features:15- You define the grid layout using rows and columns.16- Each subplot can occupy multiple cells of the grid.17- It provides more flexibility in organizing subplots of varying sizes.18 19###Parameters of subplot2grid:20- `shape`: A tuple (nrows, ncols) that specifies the number of rows and columns of the grid.21- `loc`: A tuple (row, col) that specifies the location (starting row and column) of the subplot.22- `rowspan`: The number of rows the subplot should span (optional).23- `colspan`: The number of columns the subplot should span (optional).24 25### Syntax:26```python27subplot2grid(grid_shape, loc, rowspan=1, colspan=1, **kwargs)28```29""")30 31st.write(""" 32 33```python34plt.subplot2grid(shape=(4,4),loc=(0,0),rowspan=2,colspan=2)35plt.plot([1,2,3,4,5,6],[1,2,3,4,5,6])36plt.title("linear")37 38plt.subplot2grid(shape=(4,4),loc=(0,2),rowspan=2,colspan=2)39 40plt.subplot2grid(shape=(4,4),loc=(2,0),rowspan=2,colspan=4)41 42plt.tight_layout()43st.pyplot(plt) 44```45""")46st.image("https://cdn-uploads.huggingface.co/production/uploads/66be1362737c4ed890949fa1/YLAYZhcrKmLD7u51tDWuz.png")47 48 49 50 51st.write(" axes",divider=True)52st.write(""" 53 54```python55 56fig,axes=plt.subplots(nrows=2,ncols=2,figsize=(3,3),facecolor="w")57 58axes[0][0].plot([1,2,3,4,5,6],[1,2,3,4,5,6])59axes[0][0].set_title("linear")60 61plt.tight_layout()62st.pyplot(fig)63```64""")65fig,axes=plt.subplots(nrows=2,ncols=2,figsize=(3,3),facecolor="w")66 67axes[0][0].plot([1,2,3,4,5,6],[1,2,3,4,5,6])68axes[0][0].set_title("linear")69 70plt.tight_layout()71st.pyplot(fig)72 73 74 75 76st.title(":blue[Customization in Matplotlib and Seaborn]")77st.write("",divider=True)78st.write("""79**Customization** refers to modifying the appearance and style of plots in both Matplotlib and Seaborn. This is important for improving readability, aesthetics, and for tailoring plots to meet specific requirements in presentations or reports.80 81### 1. Customization in Matplotlib82 83Matplotlib offers a wide range of customization options, which include:84 85- **Titles and Labels**: 86 You can customize the titles and axis labels of your plots. This helps in clearly describing what each plot represents.87 88- **Tick Marks**: 89 Tick marks can be adjusted to display specific data points or intervals. Customization of tick marks includes changing their appearance, positioning, and labels.90 91- **Line Styles and Colors**: 92 The lines in plots can be customized with different colors, styles (dashed, solid), and thickness, making visual data representation clearer.93 94- **Figure Size and DPI**: 95 You can control the dimensions of the plot and its resolution by customizing the figure size and dots-per-inch (DPI), which affects the sharpness of the plot.96 97- **Grid and Background**: 98 Grid lines can be added or modified, and the overall background style of the plot can be adjusted for clarity and visual appeal.99 100### 2. Customization in Seaborn101 102Seaborn builds on Matplotlib and offers additional features for easier and more aesthetically pleasing customization:103 104- **Color Palettes**: 105 Seaborn provides preset color palettes that can be used to give consistent, visually appealing color schemes to plots.106 107- **Context and Style**: 108 Seaborn allows you to change the context (scaling of plot elements) and the style of plots (e.g., `white`, `darkgrid`) to match different use cases, such as reports, presentations, or detailed analysis.109 110- **Axes Customization**: 111 Like Matplotlib, Seaborn provides built-in functions for easily adding titles, labels, and modifying axis properties.112 113- **Facet Grids and Subplots**: 114 Seaborn allows you to display multiple plots in a grid layout (e.g., facet grids), making it easy to compare datasets or categories.115 116""")117st.write(" axes",divider=True)118st.write(""" 119 120```python121st.write(" axes",divider=True)122fig = plt.figure()123axes = fig.add_axes([0, 0, 1, 1])124 125 126axes.spines["bottom"].set_color("b")127axes.spines["bottom"].set_linewidth(0.5)128axes.spines["bottom"].set_linestyle("--")129 130axes.spines["left"].set_color("r")131axes.spines["right"].set_color("k")132axes.spines["top"].set_color("g")133 134 135axes.plot([1, 2, 3], [4, 5, 6])136 137axes.set_xlim(1, 21)138axes.set_ylim(1, 21)139 140axes.set_xticks(np.arange(1, 21))141axes.set_yticks(np.arange(1, 21))142 143st.pyplot(fig)144```145""")146 147 148 149fig = plt.figure()150axes = fig.add_axes([0, 0, 1, 1])151 152 153axes.spines["bottom"].set_color("b")154axes.spines["bottom"].set_linewidth(0.5)155axes.spines["bottom"].set_linestyle("--")156 157axes.spines["left"].set_color("r")158axes.spines["right"].set_color("k")159axes.spines["top"].set_color("g")160 161 162axes.plot([1, 2, 3], [4, 5, 6])163 164axes.set_xlim(1, 21)165axes.set_ylim(1, 21)166 167axes.set_xticks(np.arange(1, 21))168axes.set_yticks(np.arange(1, 21))169 170st.pyplot(fig)171 172 173 174 175st.write("plot",divider=True)176st.write(""" 177 178```python179plt.plot([1,2,3,4,5,6,7,8],[2,3,4,5,6,7,8,9])180plt.xlim(1,21)181plt.ylim(1,21)182 183plt.xticks(np.arange(1,21))184plt.yticks(np.arange(1,21))185 186plt.show()187st.pyplot(plt)188```189""")190plt.plot([1,2,3,4,5,6,7,8],[2,3,4,5,6,7,8,9])191plt.xlim(1,21)192plt.ylim(1,21)193 194plt.xticks(np.arange(1,21))195plt.yticks(np.arange(1,21))196 197plt.show()198st.pyplot(plt)199 200 201 202 203st.write("axes",divider=True)204st.write(""" 205 206```python207fig = plt.figure()208axes = fig.add_axes([0, 0, 1, 1])209 210axes.spines["bottom"].set_color("b")211axes.spines["bottom"].set_linewidth(0.5)212axes.spines["bottom"].set_linestyle("--")213 214axes.spines["left"].set_color("r")215axes.spines["right"].set_color("k")216axes.spines["top"].set_color("g")217 218 219axes.plot([1, 2, 3], [4, 5, 6])220 221 222axes.set_xscale("log")223 224 225st.pyplot(fig)226```227""")228 229fig = plt.figure()230axes = fig.add_axes([0, 0, 1, 1])231 232axes.spines["bottom"].set_color("b")233axes.spines["bottom"].set_linewidth(0.5)234axes.spines["bottom"].set_linestyle("--")235 236axes.spines["left"].set_color("r")237axes.spines["right"].set_color("k")238axes.spines["top"].set_color("g")239 240 241axes.plot([1, 2, 3], [4, 5, 6])242 243 244axes.set_xscale("log")245 246 247st.pyplot(fig)248 249 250 251st.write(" axes : RGB",divider=True)252st.write("""253```python254fig = plt.figure(facecolor=(0.0, 0.0, 0.0))255axes = fig.add_axes([0, 0, 1, 1])256 257 258axes.spines["bottom"].set_color("b")259axes.spines["bottom"].set_linewidth(0.5)260axes.spines["bottom"].set_linestyle("--")261 262axes.spines["left"].set_color("r")263axes.spines["right"].set_color("k")264axes.spines["top"].set_color("g")265 266 267axes.plot([1, 2, 3], [4, 5, 6])268 269 270axes.set_xscale("log")271 272 273st.pyplot(fig)274 275```276""")277 278fig = plt.figure(facecolor=(0.0, 0.0, 0.0))279axes = fig.add_axes([0, 0, 1, 1])280 281 282axes.spines["bottom"].set_color("b")283axes.spines["bottom"].set_linewidth(0.5)284axes.spines["bottom"].set_linestyle("--")285 286axes.spines["left"].set_color("r")287axes.spines["right"].set_color("k")288axes.spines["top"].set_color("g")289 290 291axes.plot([1, 2, 3], [4, 5, 6])292 293 294axes.set_xscale("log")295 296 297st.pyplot(fig)298 299st.write(" axes ",divider=True)300st.write("""301```python302fig=plt.figure(facecolor=(1.0,0.70000000002,0.9000001))303axes=fig.add_axes([0,0,1,1])304```305""")306fig=plt.figure(facecolor=(1.0,0.70000000002,0.9000001))307axes=fig.add_axes([0,0,1,1])308st.pyplot(fig)309 310 311st.write(" axes:Light pink background ",divider=True)312st.write("""313```python314 315fig = plt.figure(facecolor=(1, 0, 1, 1)) 316 317 318axes = fig.add_axes([0, 0, 1, 1])319 320 321axes.spines["bottom"].set_color("b") 322axes.spines["bottom"].set_linewidth(0.5) 323axes.spines["bottom"].set_linestyle("--") 324 325 326axes.spines["left"].set_color("r") 327axes.spines["right"].set_color("k") 328axes.spines["top"].set_color("g") 329 330 331axes.set_facecolor((1.0, 0.7, 0.9)) 332 333 334axes.plot([1, 2, 3], [4, 5, 6])335 336 337axes.set_xscale("log")338 339 340axes.set_title("My Logarithmic Plot", fontsize=16, color='black') 341 342 343st.pyplot(fig)344```345""")346fig = plt.figure(facecolor=(1, 0, 1, 1)) 347 348 349axes = fig.add_axes([0, 0, 1, 1])350 351 352axes.spines["bottom"].set_color("b") 353axes.spines["bottom"].set_linewidth(0.5) 354axes.spines["bottom"].set_linestyle("--") 355 356 357axes.spines["left"].set_color("r") 358axes.spines["right"].set_color("k") 359axes.spines["top"].set_color("g") 360 361 362axes.set_facecolor((1.0, 0.7, 0.9)) 363 364 365axes.plot([1, 2, 3], [4, 5, 6])366 367 368axes.set_xscale("log")369 370 371axes.set_title("My Logarithmic Plot", fontsize=16, color='black') 372 373 374st.pyplot(fig)375 376st.write(" plt ",divider=True)377st.write("""378```python379plt.plot([3,4,5,7],[7,3,4,5])380plt.xlabel("speed")381plt.ylabel("distance")382plt.title("speed vs distance")383```384""")385 386 387 388 389plt.plot([3,4,5,7],[7,3,4,5])390plt.xlabel("speed")391plt.ylabel("distance")392plt.title("speed vs distance")393st.pyplot(plt)394 395 396 397 398 399 400 401 402 403st.title(":blue[Displaying an Image in Matplotlib]")404 405st.write("""406In Matplotlib, you can display an image using the `plt.imshow()` function, allowing you to visualize image data in your plots.407""")408 409st.write("### Explanation")410 411st.write("1. **Importing Required Libraries**: Before you can display an image, you need to import Matplotlib.")412st.code("import matplotlib.pyplot as plt")413 414st.write("2. **Reading the Image**: Use `plt.imread()` to load the image from the specified file path and return it as an array.")415st.code("img = plt.imread(r'path/to/your/image.jpg') # Replace with your actual image path")416 417st.write("""418- **Parameters**:419 - `r"path/to/your/image.jpg"`: This is the path to the image file. The `r` before the string denotes a raw string to avoid issues with backslashes.420""")421 422st.write("3. **Displaying the Image**: Use `plt.imshow()` to render the image in a plot.")423st.code("plt.imshow(img)")424 425st.write("""426- The `plt.imshow()` function supports various image formats, including JPEG and PNG.427""")428 429st.write("4. **Adjusting Axes (Optional)**: To remove axis ticks or labels for a cleaner display, use `plt.axis('off')`.")430st.code("plt.axis('off') # Hides the axis")431 432st.write("5. **Showing the Image**: Finally, call `plt.show()` to render the plot containing the image.")433st.code("plt.show()")434 435st.write("### Example Code")436st.code("""437import matplotlib.pyplot as plt438 439# Step 1: Read the image440img = plt.imread(r'path/to/your/image.jpg') # Replace with your actual image path441 442# Step 2: Display the image443plt.imshow(img)444 445# Optional: Hide the axis446plt.axis('off')447 448# Step 3: Show the image449plt.show()450""")451 452 453 454 