Ashish Agarwal
Ashish Agarwal

Reputation: 6283

How to draw BarPlot or Histogram using Subplot in MatplotLib?

Tried to Refer Documentation https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots.html

However, I am unable to find exact way to fulfill my requirement.

Using Demo code I am able to draw only LineGraph. However, I am required to draw Bar Graph.

fig, axes = plt.subplots(1, 2, figsize=(10,4))
x = np.linspace(0, 5, 11)
axes[0].plot(x, x**2, x, np.exp(x),x,20*x)
axes[0].set_title("Normal scale")
axes[0].plot

axes[1].plot(x, x**2, x, np.exp(x))
axes[1].set_yscale("log")
axes[1].set_title("Logarithmic scale (y)");

Please feel free to correct my approach or guide me as I have just started learning. enter image description here

Upvotes: 1

Views: 2210

Answers (2)

Ashish Agarwal
Ashish Agarwal

Reputation: 6283

After going through the API documentation from Matplotlip Subplot Axes, I found ways to draw different graph not just Line graph.

https://matplotlib.org/api/axes_api.html

DEFAULT:-

  • axes[0].plot by-default draws line graph.

CUSTOM GRAPH:-

  • axes[0].bar can be used to draw BAR graph in selected Subplot

  • axes[0].scatter can be used to draw Scatter graph in selected Subplot

  • axes[0].hist can be used to draw a histogram. in selected Subplot

Like above example more graph can be drawn with below API:- enter image description here

Upvotes: 1

Tacratis
Tacratis

Reputation: 1055

If you specify exactly what you want to use for the bar and hist, I can modify, but generally it is simply changing the plot to the type of chart you need

import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(1, 2, figsize=(10,4))
x = np.linspace(0, 5, 11)
axes[0].bar(x,x**2) # bar plot
axes[0].set_title("Normal scale")
axes[0].plot

axes[1].hist(x) # histogram
axes[1].set_yscale("log")
axes[1].set_title("Logarithmic scale (y)");

plt.show()

Upvotes: 3

Related Questions