YouTip LogoYouTip

Matplotlib Bar

We can use the `bar()` method in `pyplot` to draw a bar chart. The syntax for the `bar()` method is as follows: matplotlib.pyplot.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs) **Parameter Description:** **x**: Array of floats, the x-axis data for the bar chart. **height**: Array of floats, the height of the bars. **width**: Array of floats, the width of the bars. **bottom**: Array of floats, the y-coordinate of the base of the bars, default is 0. **align**: The alignment of the bars relative to the x-coordinates. 'center' centers the bars on the x positions, which is the default. 'edge' aligns the left edge of the bars with the x positions. To align the right edge of the bars, you can pass a negative width value and use align='edge'. ****kwargs**: Other parameters. In the following example, we simply use `bar()` to create a bar chart: ## Example import matplotlib.pyplot as plt import numpy as np x = np.array(["-1","-2","-3","C-"]) y = np.array([12,22,6,18]) plt.bar(x,y) plt.show() The result is as follows: !(#) A vertical bar chart can be created using the `barh()` method: ## Example import matplotlib.pyplot as plt import numpy as np x = np.array(["-1","-2","-3","C-"]) y = np.array([12,22,6,18]) plt.barh(x,y) plt.show() The result is as follows: !(#) Setting the color of the bar chart: ## Example import matplotlib.pyplot as plt import numpy as np x = np.array(["-1","-2","-3","C-"]) y = np.array([12,22,6,18]) plt.bar(x, y, color ="#4CAF50") plt.show() The result is as follows: !(#) Customizing the color of each bar: ## Example import matplotlib.pyplot as plt import numpy as np x = np.array(["-1","-2","-3","C-"]) y = np.array([12,22,6,18]) plt.bar(x, y,color =["#4CAF50","red","hotpink","#556B2F"]) plt.show() The result is as follows: !(#) Setting the width of the bars: use the **width** parameter for the `bar()` method, and the **height** parameter for the `barh()` method. ## Example import matplotlib.pyplot as plt import numpy as np x = np.array(["-1","-2","-3","C-"]) y = np.array([12,22,6,18]) plt.bar(x, y, width =0.1) plt.show() The result is as follows: !(#) ## Example import matplotlib.pyplot as plt import numpy as np x = np.array(["-1","-2","-3","C-"]) y = np.array([12,22,6,18]) plt.barh(x, y, height =0.1) plt.show() The result is as follows: !(#)
← Java String CharatCharacter Islowercase β†’