The circular color gradient is useful in various fields, such as art, design, and photography, for selecting color schemes, Let’s see how to make a circular color gradient ?
A circular color gradient is a powerful tool for generating visually appealing graphics and data visualizations. it is a smooth transition of colors arranged in a circular pattern, where the colors change gradually from one to the next. Python provides a range of libraries and methods to create circular color gradients, including Pillow, numpy, and matplotlib.
In this tutorial, we will walk through the steps to make a circular color gradient in Python using the above-mentioned libraries. We will also cover different methods to make a circular color gradient and provide a comprehensive, step-by-step guide to help you create your own.
Using Matplotlib Library
In Python, the Matplotlib library provides various methods to create circular color gradients. In this tutorial, we will focus on these two specific methods:
- The pcolormesh() Method
- The imshow() Method
Use pcolormesh() Method
# Import necessary libraries and modules import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap # Define the color map with a list of colors and their corresponding positions cmap = LinearSegmentedColormap.from_list("my_cmap", [(0, "red"), (0.2, "green"), (0.4, "white"), (0.6, "pink"), (0.8, "yellow"), (1, "blue")]) # Create a 2D meshgrid of points spanning a square region x= np.linspace(-1,1,100) y= np.linspace(-1,1,100) X, Y = np.meshgrid(x,y) # Calculate the distance from the center of the meshgrid to each point on the grid Radius = np.sqrt(X**2 + Y**2) # Create a figure with a size of 5x5 inches, and plot the color gradient using pcolormesh function plt.figure(figsize=(5,5)) plt.pcolormesh(X, Y, Radius, cmap=cmap) # Turn off the axis display plt.axis("off") #set title for plot plt.title('Circular Gradient',color='b') # Show the plot plt.show() # Print message print("Congrats! You have successfully created Circular gradient")
This code generates a circular gradient using a custom color map and the pcolormesh method from the matplotlib library. A detailed description of the code is given below.
In the above code, the numpy and matplotlib modules were imported. A linear segmented color map was created using the LinearSegmentedColormap method from the matplotlib.colors module. The color map was defined with the name my_cmap and with a list of color tuples, where the first element of each tuple specifies the position in the gradient and the second element specifies the color at that position.
Then, a meshgrid was generated using the np.meshgrid method from numpy, which created a 2D array of coordinates that cover the specified range. In this case, 100 points were generated between -1 and 1 for both the x and y axes.
Next, the radius was calculated using the meshgrid values X and Y. This represents the distance of each point from the origin (0, 0) in the coordinate system.
After that, a figure was created with a size of 5×5 using the plt.figure method, and a color mesh plot was generated using the plt.pcolormesh method. This method takes the X, Y, and R arrays as inputs, along with the cmap parameter that specifies the color map to use.
The plot’s axes were turned off using the plt.axis method, and the plot was displayed using the plt.show method. Finally, a message was printed to the console to indicate that a circular gradient was created.
Using imshow() Method
import numpy as np import matplotlib.pyplot as plt #Define a function to generate the circular gradient using a sine wave. def gradient(x): return np.sin(4 * np.pi * x) #Generate a grid of x and y values using numpy meshgrid. X, Y = np.meshgrid(np.linspace(0, 1, 512), np.linspace(0, 1, 512)) #Calculate the distance from the center of the grid to each point. R = np.sqrt((X - 0.5)**2 + (Y - 0.5)**2) #Generate the circular gradient using the gradient function and distance matrix. Z = gradient(R) #Create a figure to display the circular gradient. plt.figure(figsize=(5, 5)) #Display the circular gradient using the 'jet' colormap, with axes limits and no tick marks. plt.imshow(Z, cmap='jet') plt.axis('off') #Add a title to the figure. plt.title('Circular Gradient Using imshow') #Show the figure. plt.show()
The above code creates a circular gradient using the imshow() method in matplotlib. The gradient is defined by the method gradient(x), which returns the sine of 4 times pi times x. The np.meshgrid() method creates a grid of points on the x and y axes, with 512 points in each direction. The distance from the center of the grid to each point is calculated using the Euclidean distance formula and stored in the array R. The gradient() method is then called with the values in R, and the resulting array is stored in Z.
The imshow() method displays the gradient as an image, with the jet colormap applied. The axis() method is used to set the aspect ratio to be equal and remove the axis labels. Finally, a title is added to the plot and it is displayed using plt.show().
import numpy as np import matplotlib.pyplot as plt # Set the size of the Image image_size = 512 # Create a meshgrid for the x and y coordinates of the image x, y = np.meshgrid(np.linspace(-1, 1, image_size), np.linspace(-1, 1, image_size)) # Calculate the radius from the center of the Image radius = np.sqrt(x**2 + y**2) # Create a circular mask with a radius of 1 mask = radius <= 1 # Calculate the angle of each point angle = np.arctan2(y, x) # Create the circular gradient gradient = (1 + np.sin(6*np.pi*radius)) * angle**2 # Apply the mask to the gradient to create a circular gradient gradient = np.ma.array(gradient, mask=~mask) # Display the Image plt.figure(figsize=(5,5)) plt.imshow(gradient, cmap='jet', extent=[-1, 1, -1, 1]) #Add a title to the figure. plt.title('Circular Gradient Using Numpy') plt.axis('off') plt.show()
The code generated a circular gradient using NumPy and Matplotlib. The first few lines of the code defined the size and center of the circle to be generated and then created a meshgrid of x and y coordinates using NumPy.
Next, a circular mask was created to limit the gradient to the inside of the circle, and a sine wave was used to calculate the gradient values. The gradient values were then converted to a masked array using NumPy, with the mask used to remove values outside the circle.
Finally, Matplotlib was used to display the gradient as an image using the imshow method. The axis was set to equal and turned off to display only the Image, and the color map was set to ‘inferno’ to show a range of colors from dark to light. The resulting image was displayed using the show() method.
from PIL import Image, ImageDraw # Define width and height of Image W, H = 200, 200 # create a new image with white background my_img = Image.new( mode="RGB", size= (W, H),color='white') # create a draw object for the Image draw_obj = ImageDraw.Draw(my_img) # set the starting and ending angles for the pie slices starting_angle = 0 ending_angle = 180 # define the shape of the pie slices shape=[20, 50, 180, 180] # define the list of colors for the pie slices colors_list = ['yellow', 'lime', 'pink'] # draw each pie slice with a different color for j, color in enumerate(colors_list): draw_obj.pieslice(shape, starting_angle, ending_angle, fill=color, outline="white", width=1) # increment the angles for the next slice starting_angle += 90 ending_angle += 90 # add a title to the Image draw_obj.text((20, 20), "Circular Gradient Using PIL", fill="black") # display the Image my_img.show() # save the Image my_img.save('circular_img.png')
In the given code, a circular gradient image was created using the PIL library in Python.
First, a new image was created with a white background using the Image.new() method. Then, an ImageDraw object was created to draw on the Image.
A pie slice shape was defined using the pieslice() method, which takes arguments for the shape coordinates, starting and ending angles, fill color, outline color, and width. A list of colors was also defined to use for the fill colors.
A for loop was used to draw three pie slices, each with a different color from the colors_list. The starting and ending angles were updated in each iteration to create the circular gradient effect.
A text label was added to the Image using the text() method, and the Image was displayed using the show() method. In the end, the Image is saved in the current folder as circular_img.png
In conclusion, circular color gradients can be easily created in Python using a variety of libraries and methods. In this tutorial, we explored different methods to make a circular color gradient in Python, using pcolormesh(), imshow(), and PIL to create stunning circular color gradients with different approaches. We provided step-by-step instructions to guide you through the process. Whether you’re a data scientist or a graphic designer, mastering circular color gradients in Python can take your visualizations to the next level.
Check here to know how to convert a column in text output in python using NumPy
Good Luck with your Learning !!