Hello,
I have a graph window that I would like to split into two (keep the same size window) but split.
On a previous none class example I used this:
fig_2, (ax, ax1) = plt.subplots(2, 1, figsize=(6, 3.5))
However I am now trying to do this with classes, but cannot workout how to tweak to add (ax, ax1)
self.ax = self.fig.add_subplot(111)
Im sure its something simple but I cannot get the syntax correct.
Thanks
The following is a class where you can pass in your data - multiple at the time of instantiation. For now, only the title of each graph is passed in. However, you can elaborate further by including the x and y axis titles which you can do easily by expanding on the information that is included in the dictionary.
import matplotlib.pyplot as plt
class DataVisualizer:
def __init__(self, data_dict):
self.data = data_dict # your data assigned to instance attribute
# 1. Initialize the figure and subplots - *per your line in your post
self.fig, self.axs = plt.subplots(nrows=len(data_dict), ncols=1, figsize=(8, 6))
# Ensure axs is always a list for consistency
if len(data_dict) == 1:
self.axs = [self.axs]
def plot_all(self):
"""Iterates through data and plots on corresponding axes."""
for i, (title, values) in enumerate(self.data.items()):
ax = self.axs[i]
ax.plot(values, marker='o', linestyle='-')
ax.set_title(title)
# ax.set_gid(True)
self.fig.tight_layout() # Prevents overlapping labels
def show(self):
plt.show()
# Example data for two - can have multiple data sets
my_data = {
"Sales Over Time": [10, 20, 15, 30],
"Revenue Trends": [100, 120, 130, 150],
"Testing Data": [1,2,3,4]
}
plt.style.use('dark_background') # if not interested in dark mode, comment out or delete
viz = DataVisualizer(my_data) # Create instance (object) with data passed in at instantiation
viz.plot_all()
viz.show()
This is a bit off topic, but did you mean “matplotlib” that got autocorrected to “metasploit”? If so, could you edit the topic for people who may be searching and have your same problem in the future?