Complete the code to create a horizontal bar chart using plt.barh.
import matplotlib.pyplot as plt categories = ['A', 'B', 'C'] values = [10, 15, 7] plt.[1](categories, values) plt.show()
The plt.barh function creates a horizontal bar chart. The other options create different types of plots.
Complete the code to label the x-axis of the horizontal bar chart.
import matplotlib.pyplot as plt categories = ['X', 'Y', 'Z'] values = [5, 8, 12] plt.barh(categories, values) plt.[1]('Value Count') plt.show()
The x-axis label is set with plt.xlabel. Since the bars are horizontal, the values are along the x-axis.
Fix the error in the code to correctly display the horizontal bar chart with custom colors.
import matplotlib.pyplot as plt categories = ['Red', 'Green', 'Blue'] values = [3, 6, 9] colors = ['red', 'green', 'blue'] plt.barh(categories, values, color=[1]) plt.show()
The color parameter expects a list of color names or codes. Passing the variable colors is correct. Passing a string or wrong variable name causes errors.
Fill both blanks to create a horizontal bar chart with categories sorted by values in descending order.
import matplotlib.pyplot as plt categories = ['Cat1', 'Cat2', 'Cat3'] values = [20, 10, 30] sorted_pairs = sorted(zip(values, categories), key=[1], reverse=[2]) sorted_values, sorted_categories = zip(*sorted_pairs) plt.barh(sorted_categories, sorted_values) plt.show()
We sort by the first element of each pair (the value) using lambda x: x[0]. To get descending order, reverse=True is needed.
Fill all three blanks to create a horizontal bar chart with labels showing the value at the end of each bar.
import matplotlib.pyplot as plt categories = ['A', 'B', 'C'] values = [7, 12, 5] bars = plt.barh(categories, values) for bar in bars: width = bar.[1]() plt.text(width + [2], bar.[3](), str(int(width)), va='center') plt.show()
get_height() which is for vertical bars.get_x() instead of get_y() for vertical position.bar.get_width() gets the length of the horizontal bar. We add a small offset (0.1) to place the label slightly to the right. bar.get_y() gets the vertical position of the bar for correct label placement.