Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Articles by Rishikesh Kumar Rishi
Page 69 of 102
How to plot a confusion matrix with string axis rather than integer in Python?
A confusion matrix with string labels provides better readability than numeric indices. In Python, we can create such matrices using matplotlib and sklearn.metrics by customizing the axis labels with descriptive strings. Basic Setup First, let's import the required libraries and prepare sample data − import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix import numpy as np # Sample data - actual vs predicted classifications actual = ['business', 'health', 'business', 'tech', 'health', 'tech'] predicted = ['business', 'business', 'business', 'tech', 'health', 'business'] # Define string labels labels = ['business', 'health', 'tech'] print("Actual:", actual) print("Predicted:", predicted) print("Labels:", ...
Read MoreSuperscript in Python plots
Superscript notation is essential for displaying scientific formulas and units in Python plots. Matplotlib supports LaTeX-style mathematical notation using the $\mathregular{}$ syntax to create superscripts and subscripts in titles, axis labels, and legends. Basic Superscript Syntax Use $\mathregular{text^{superscript}}$ format where the caret ^ indicates superscript and curly braces {} contain the superscript text ? import matplotlib.pyplot as plt # Simple superscript example plt.figure(figsize=(6, 4)) plt.text(0.5, 0.5, r'$\mathregular{x^2}$', fontsize=20, ha='center') plt.text(0.5, 0.3, r'$\mathregular{E=mc^2}$', fontsize=16, ha='center') plt.xlim(0, 1) plt.ylim(0, 1) plt.title('Basic Superscript Examples') plt.show() Physics Formula Plot with Superscripts Let's create a force vs ...
Read MoreLogarithmic Y-axis bins in Python
To plot logarithmic Y-axis bins in Python, we can use matplotlib's yscale() method to set a logarithmic scale. This is particularly useful when your data spans several orders of magnitude, making it easier to visualize trends that would be compressed on a linear scale. Steps to Create Logarithmic Y-axis Plot Create x and y data points using NumPy Set the Y-axis scale using the yscale() method Plot the x and y points using the plot() method Add labels and legend for better visualization Display the figure using the show() method Example Here's how to ...
Read MoreHow to plot a time series in Python?
To plot a time series in Python using matplotlib, we can take the following steps − Create x and y points, using numpy. Plot the created x and y points using the plot() method. To display the figure, use the show() method. Basic Time Series Plot Here's a simple example that creates hourly data points for a full day ? import matplotlib.pyplot as plt import datetime import numpy as np plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True # Create datetime points for 24 hours x = np.array([datetime.datetime(2021, 1, 1, i, 0) ...
Read MoreHow to hide ticks label in Python but keep the ticks in place?
When working with matplotlib plots, you might need to hide tick labels while keeping the tick marks visible. This is useful for creating cleaner visualizations or when labels would be redundant or cluttered. Basic Approach The simplest method is using plt.xticks() or plt.yticks() with empty labels ? import matplotlib.pyplot as plt import numpy as np # Create sample data x = np.linspace(1, 10, 100) y = np.log(x) # Create the plot plt.figure(figsize=(8, 4)) plt.plot(x, y, 'b-', linewidth=2) # Hide x-axis labels but keep ticks plt.xticks(ticks=range(1, 11), labels=[]) # Add title and labels ...
Read MoreHow to get the color of the most recent plotted line in Python?
When working with matplotlib plots, you often need to retrieve the color of the most recently plotted line for further customization or analysis. Python provides the get_color() method to access line properties. Basic Example Here's how to get the color of the most recent plotted line ? import numpy as np import matplotlib.pyplot as plt # Set figure properties plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True # Create data points x = np.linspace(1, 10, 1000) y = np.linspace(10, 20, 1000) # Plot line and capture the line object line, = plt.plot(x, y, c="red", ...
Read MoreHow to put a legend outside the plot with Pandas?
When creating plots with Pandas, legends can sometimes overlap with the plot area. Using bbox_to_anchor parameter in legend() allows you to position the legend outside the plot boundaries for better visibility. Basic Example Here's how to create a DataFrame and place the legend outside the plot ? import pandas as pd import matplotlib.pyplot as plt # Set figure size for better display plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True # Create sample data data = {'Column 1': [i for i in range(10)], 'Column 2': [i * ...
Read MoreHow to overplot a line on a scatter plot in Python?
Overplotting a line on a scatter plot combines scattered data points with a trend line or reference line. This technique is useful for showing relationships, trends, or theoretical models alongside actual data points. Basic Approach Create the scatter plot first using scatter(), then add the line using plot() on the same axes ? import matplotlib.pyplot as plt import numpy as np # Generate sample data x_data = np.linspace(0, 10, 20) y_data = 2 * x_data + 1 + np.random.normal(0, 2, 20) # Linear with noise # Create scatter plot plt.figure(figsize=(8, 6)) plt.scatter(x_data, y_data, ...
Read MoreBarchart with vertical labels in Python/Matplotlib
When creating bar charts in Python using Matplotlib, you can rotate axis labels to improve readability, especially when dealing with long label names. The xticks() function with the rotation parameter allows you to set labels vertically or at any angle. Basic Bar Chart with Vertical Labels Here's how to create a bar chart with vertical x-axis labels − from matplotlib import pyplot as plt bars_heights = [14, 8, 10] bars_label = ["A label", "B label", "C label"] plt.bar(range(len(bars_label)), bars_heights) plt.xticks(range(len(bars_label)), bars_label, rotation='vertical') plt.show() Different Rotation Angles You can specify custom angles ...
Read MoreHow to save a figure remotely with pylab in Python?
Using the savefig() method of the pyplot package, we can save matplotlib figures to remote locations or specific directories by providing the complete file path. Setting Up the Backend When saving figures without displaying them, it's recommended to use the 'Agg' backend, which is designed for file output ? import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt Basic Figure Saving Create a simple plot and save it to the current directory ? import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt # Create a simple plot plt.plot([1, 2, 3, ...
Read More