Python provides powerful libraries like Matplotlib and Plotly for creating various types of plots and graphs. In this tutorial, we will explore how to create 2D and 3D plots and graphs and integrate them into a website or export them to Excel.
1. Creating a 2D Plot with Matplotlib:
Matplotlib is a versatile library for creating static, animated, and interactive visualizations in Python. Let’s create a simple 2D plot:
import matplotlib.pyplot as plt
import numpy as np
# Generate data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create plot
plt.figure(figsize=(8, 6))
plt.plot(x, y, label='sin(x)')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.title('2D Plot with Matplotlib')
plt.legend()
plt.grid(True)
plt.savefig('2d_plot.png') # Save the plot as an image
plt.show()
Output:

Explanation of the above code:
import matplotlib.pyplot as plt: Imports thepyplotmodule from thematplotliblibrary and assigns it the aliasplt, which is a common convention.import numpy as np: Imports thenumpylibrary and assigns it the aliasnp, which is another common convention.numpyis used here to generate the data for the plot.x = np.linspace(0, 10, 100): Generates an array of 100 evenly spaced numbers between 0 and 10 and assigns it to the variablex. This array will be used as the x-axis values for the plot.y = np.sin(x): Calculates the sine of each element in the arrayxand assigns it to the variabley. This array will be used as the y-axis values for the plot.plt.figure(figsize=(8, 6)): Creates a new figure with a specified figure size of 8 inches by 6 inches. All subsequent plotting commands will be applied to this figure.plt.plot(x, y, label='sin(x)'): Plotsxon the x-axis andyon the y-axis, creating a line plot. Thelabelparameter specifies the label for the plot, which will be used in the legend.plt.xlabel('x'): Adds a label to the x-axis with the text'x'.plt.ylabel('sin(x)'): Adds a label to the y-axis with the text'sin(x)'.plt.title('2D Plot with Matplotlib'): Adds a title to the plot with the text'2D Plot with Matplotlib'.plt.legend(): Displays the legend for the plot, which includes the label specified in theplotfunction.plt.grid(True): Adds a grid to the plot for better readability.plt.savefig('2d_plot.png'): Saves the plot as an image file named'2d_plot.png'.plt.show(): Displays the plot on the screen.
Beginner? Didn’t quite understand the code, let me make it simple
- Importing Libraries: We’re bringing in tools (
matplotlibandnumpy) that help us create plots and do math easily. - Generating Data: We’re creating a list of numbers (
x) starting from 0 to 10, split into 100 evenly spaced points. This will be our horizontal axis on the plot. Another list (y) is calculated based on the sine function, which will be our vertical axis. - Creating a Blank Canvas: We’re setting up a blank space (like a canvas) where we’ll draw our plot. We’re specifying its size to be 8 inches wide and 6 inches tall.
- Drawing the Plot: We’re actually drawing the plot now. We’re plotting the
xvalues against theyvalues. This creates a curve that represents the sine function. We’re also labeling this curve as “sin(x)” for the legend. - Adding Labels: We’re labeling the horizontal axis as “x” and the vertical axis as “sin(x)”.
- Adding a Title: We’re giving our plot a title, which is “2D Plot with Matplotlib”.
- Showing the Legend: We’re showing a small box that explains what the curve represents. In this case, it says “sin(x)”.
- Adding a Grid: We’re adding a grid to our plot, which makes it easier to read.
- Saving the Plot: We’re saving our plot as an image file named “2d_plot.png”. This allows us to use the plot in other places, like in a document or on a website.
- Displaying the Plot: Finally, we’re showing the plot on the screen for us to see and analyze.
2. Creating a 3D Plot with Plotly:
Plotly is a library for creating interactive plots and dashboards. Let’s create a 3D surface plot:
import plotly.graph_objects as go
import numpy as np
# Generate data
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(np.sqrt(x**2 + y**2))
# Create plot
fig = go.Figure(data=[go.Surface(z=z, x=x, y=y)])
fig.update_layout(title='3D Plot with Plotly',
scene=dict(
xaxis_title='X',
yaxis_title='Y',
zaxis_title='Z'),
autosize=False,
width=800,
height=600)
fig.write_html('3d_plot.html') # Save the plot as an HTML file
fig.show()
Output:
Explanation of the above code:
- Importing Libraries: We’re importing the
graph_objectsmodule from theplotlylibrary asgo, and thenumpylibrary asnp. Plotly is used for creating interactive plots, and NumPy is used for numerical operations. - Generating Data: We’re creating a grid of points in the x-y plane. The
linspacefunction from NumPy generates 100 equally spaced points between -5 and 5 for bothxandy. - Creating a Meshgrid: We’re using
meshgridto create a 2D grid fromxandy. This is used to create 3D plots where each point has anx,y, andzvalue. - Calculating Z-values: We’re calculating the
zvalues for each point in the meshgrid using the formulaz = sin(sqrt(x**2 + y**2)). This gives us a surface that resembles a cone. - Creating the Plot: We’re creating a new figure (
fig) using Plotly’sFigureclass. We’re adding a 3D surface plot to the figure using theSurfacetrace type, with thez,x, andyvalues as arguments. - Updating the Layout: We’re updating the layout of the figure to set the title and axis titles. We’re also setting the width and height of the plot and disabling autosizing.
- Saving the Plot: We’re saving the plot as an HTML file named “3d_plot.html”. This HTML file can be opened in a web browser to view the interactive 3D plot.
- Displaying the Plot: Finally, we’re displaying the plot using the
showmethod, which opens the plot in a new browser window for interactive exploration.
Integrating plots into a website involves embedding the saved image (for 2D plots) or the saved HTML file (for 3D plots) into the HTML code of your website. Here’s how you can do it:
or 2D Plots (Saved as an Image):
- Save the 2D plot as an image using
plt.savefig('2d_plot.png'). - Use an
<img>tag in your HTML code to embed the image into your website:
<img src="2d_plot.png" alt="2D Plot">
- The
srcattribute specifies the path to the image file (in this case, “2d_plot.png”). - The
altattribute provides alternative text for the image, which is displayed if the image cannot be loaded.
For 3D Plots (Saved as an HTML File):
- Save the 3D plot as an HTML file using
fig.write_html('3d_plot.html'). - Use an
<iframe>tag in your HTML code to embed the HTML file into your website:
<iframe src="3d_plot.html" width="800" height="600"></iframe>
- The
srcattribute specifies the path to the HTML file (in this case, “3d_plot.html”). - The
widthandheightattributes specify the dimensions of the iframe, which should match the dimensions set infig.update_layout.
By embedding the plots in this way, you can display them within your website, allowing users to interact with and explore the data visually.
ntegrating plots into an Excel sheet involves embedding the saved image (for 2D plots) directly into a worksheet. Here’s how you can do it:
- For 2D Plots (Saved as an Image):
- Save the 2D plot as an image using
plt.savefig('2d_plot.png'). - Insert the image into an Excel worksheet using the “Insert” tab and selecting “Pictures”:
- Click on the cell where you want to insert the image.
- Go to the “Insert” tab on the Excel ribbon.
- Click on “Pictures” and select the saved image (“2d_plot.png”).
- Resize and position the image as desired within the worksheet.
- The image will be embedded into the Excel worksheet, allowing you to view the 2D plot directly within Excel.
- Save the 2D plot as an image using
2. Here’s how you can embed a Plotly 3D plot into an Excel worksheet:
import plotly.graph_objects as go
import numpy as np
from openpyxl import Workbook
from openpyxl.drawing.image import Image
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import io
# Generate data
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(np.sqrt(x**2 + y**2))
# Create plot
fig = go.Figure(data=[go.Surface(z=z, x=x, y=y)])
fig.update_layout(title='3D Plot with Plotly',
scene=dict(
xaxis_title='X',
yaxis_title='Y',
zaxis_title='Z'),
autosize=False,
width=800,
height=600)
# Save the plot as a PNG image
fig.write_image('3d_plot.png')
# Create a new Excel workbook
wb = Workbook()
ws = wb.active
# Insert the plot image into the Excel sheet
img = Image('3d_plot.png')
ws.add_image(img, 'A1')
# Save the workbook
wb.save('plot_in_excel.xlsx')

Note: You can click on the link in the above image to see the fully functional 3d image. Similarly, you can also add hyperlinks.
In conclusion, creating and embedding 2D and 3D plots and graphs using Python offers a powerful way to visualize data and present it in various formats. Matplotlib and Plotly are two popular libraries that provide extensive functionality for generating these visualizations.
For integrating these plots into Excel, saving them as images and inserting them into Excel sheets is a straightforward approach. However, for more interactive plots, embedding HTML files or using web browser controls in VBA may be necessary.
Similarly, embedding these plots into a website involves saving the plots as images or HTML files and using appropriate HTML tags to display them on the webpage. This allows for dynamic and interactive data visualization on web platforms.
Overall, Python’s versatility and the rich ecosystem of libraries make it a valuable tool for creating and embedding plots and graphs in various applications, enhancing data analysis and presentation capabilities.





Leave a Reply