overlapping in matplotlib plot

Question:

I am comparing the execution time of an exhaustive search and genetic algorithm along with sample solutions.
In the graph below, I am trying to improve the readability of my graph. However, they overlap with each other.

Sample Code:

import matplotlib.pyplot as plt

# define the data
exhaustive_search = [72, 9139]
genetic_algorithm = [52.8, 200]

# create a figure with two subplots
fig, (ax1, ax2) = plt.subplots(1, 2)

# set the spacing between the subplots
fig.subplots_adjust(wspace=0.1)

# create a bar chart for execution time
ax1.bar(['Exhaustive Search', 'Genetic Algorithm'], [exhaustive_search[0], genetic_algorithm[0]], width=0.4, align='edge')
ax1.set_xlabel('Algorithm')
ax1.set_ylabel('Execution Time (s)')

# create a bar chart for number of solutions
ax2.bar(['Exhaustive Search', 'Genetic Algorithm'], [exhaustive_search[1], genetic_algorithm[1]], width=-0.4, align='edge')
ax2.set_xlabel('Algorithm')
ax2.set_ylabel('Number of Solutions')

# add a title to the figure
fig.suptitle('Execution Time and Solution Comparison')

# show the plot
plt.show()

Output:

enter image description here

How can I solve this issue or further improve it for a reader?

I am comparing the execution time of an exhaustive search and genetic algorithm along with sample solutions. I am trying to improve the readability of my graph. However, they overlap with each other.

How can I solve this issue or further improve it for a reader?

Asked By: Beta

||

Answers:

You can set a larger figsize for you plt.subplots.
Also, I removed fig.subplots_adjust(wspace=0.1) and used plt.tight_layout() instead.

I think you want the ticks aligned at the center of the bars, so I changed the tick align for your bar plots to 'center'.

import matplotlib.pyplot as plt

# define the data
exhaustive_search = [72, 9139]
genetic_algorithm = [52.8, 200]

# create a figure with two subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))

# create a bar chart for execution time
ax1.bar(['Exhaustive Search', 'Genetic Algorithm'], [exhaustive_search[0], genetic_algorithm[0]], width=0.4,
        align='center')
ax1.set_xlabel('Algorithm')
ax1.set_ylabel('Execution Time (s)')

# create a bar chart for number of solutions
ax2.bar(['Exhaustive Search', 'Genetic Algorithm'], [exhaustive_search[1], genetic_algorithm[1]], width=-0.4,
        align='center')
ax2.set_xlabel('Algorithm')
ax2.set_ylabel('Number of Solutions')

# add a title to the figure
fig.suptitle('Execution Time and Solution Comparison')

# show the plot
plt.tight_layout()
plt.show()

enter image description here

Answered By: コリン