, ,

Creating 2D and 3D Plots and Graphs Using Python and Embedding them into Excel or Website

Creating 2D and 3D Plots and Graphs Using Python and Embedding them into Excel or Website

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:

  1. import matplotlib.pyplot as plt: Imports the pyplot module from the matplotlib library and assigns it the alias plt, which is a common convention.
  2. import numpy as np: Imports the numpy library and assigns it the alias np, which is another common convention. numpy is used here to generate the data for the plot.
  3. x = np.linspace(0, 10, 100): Generates an array of 100 evenly spaced numbers between 0 and 10 and assigns it to the variable x. This array will be used as the x-axis values for the plot.
  4. y = np.sin(x): Calculates the sine of each element in the array x and assigns it to the variable y. This array will be used as the y-axis values for the plot.
  5. 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.
  6. plt.plot(x, y, label='sin(x)'): Plots x on the x-axis and y on the y-axis, creating a line plot. The label parameter specifies the label for the plot, which will be used in the legend.
  7. plt.xlabel('x'): Adds a label to the x-axis with the text 'x'.
  8. plt.ylabel('sin(x)'): Adds a label to the y-axis with the text 'sin(x)'.
  9. plt.title('2D Plot with Matplotlib'): Adds a title to the plot with the text '2D Plot with Matplotlib'.
  10. plt.legend(): Displays the legend for the plot, which includes the label specified in the plot function.
  11. plt.grid(True): Adds a grid to the plot for better readability.
  12. plt.savefig('2d_plot.png'): Saves the plot as an image file named '2d_plot.png'.
  13. plt.show(): Displays the plot on the screen.

Beginner? Didn’t quite understand the code, let me make it simple

  1. Importing Libraries: We’re bringing in tools (matplotlib and numpy) that help us create plots and do math easily.
  2. 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.
  3. 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.
  4. Drawing the Plot: We’re actually drawing the plot now. We’re plotting the x values against the y values. This creates a curve that represents the sine function. We’re also labeling this curve as “sin(x)” for the legend.
  5. Adding Labels: We’re labeling the horizontal axis as “x” and the vertical axis as “sin(x)”.
  6. Adding a Title: We’re giving our plot a title, which is “2D Plot with Matplotlib”.
  7. Showing the Legend: We’re showing a small box that explains what the curve represents. In this case, it says “sin(x)”.
  8. Adding a Grid: We’re adding a grid to our plot, which makes it easier to read.
  9. 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.
  10. 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:

  1. Importing Libraries: We’re importing the graph_objects module from the plotly library as go, and the numpy library as np. Plotly is used for creating interactive plots, and NumPy is used for numerical operations.
  2. Generating Data: We’re creating a grid of points in the x-y plane. The linspace function from NumPy generates 100 equally spaced points between -5 and 5 for both x and y.
  3. Creating a Meshgrid: We’re using meshgrid to create a 2D grid from x and y. This is used to create 3D plots where each point has an x, y, and z value.
  4. Calculating Z-values: We’re calculating the z values for each point in the meshgrid using the formula z = sin(sqrt(x**2 + y**2)). This gives us a surface that resembles a cone.
  5. Creating the Plot: We’re creating a new figure (fig) using Plotly’s Figure class. We’re adding a 3D surface plot to the figure using the Surface trace type, with the z, x, and y values as arguments.
  6. 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.
  7. 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.
  8. Displaying the Plot: Finally, we’re displaying the plot using the show method, 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 src attribute specifies the path to the image file (in this case, “2d_plot.png”).
  • The alt attribute 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 src attribute specifies the path to the HTML file (in this case, “3d_plot.html”).
  • The width and height attributes specify the dimensions of the iframe, which should match the dimensions set in fig.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:

  1. 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.

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.

    More on Graphs in Excel

    Author

    Sona Avatar

    Written by

    Leave a Reply

    Trending

    CodeMagnet

    Your Magnetic Resource, For Coding Brilliance

    Programming Languages

    Web Development

    Data Science and Visualization

    Career Section

    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
         crossorigin="anonymous"></script>