Matplotlib基线绘制

绘制余弦正弦图像,横轴坐标为(-π, π)
1、 基本图像绘制

import matplotlib.pyplot as plt
import numpy as np

def main():

    x = np.linspace(-np.pi, np.pi, 256, endpoint=True)  # 从 -pi到pi,有256个点
    c = np.cos(x)
    s = np.sin(x)
    plt.figure(1)
    plt.plot(x, c)  # 第一个参数是自变量,第二个参数是因变量
    plt.plot(x, s)
    plt.show()

if __name__ == "__main__":
    main()

结果为:
在这里插入图片描述
2、属性变化

import matplotlib.pyplot as plt
import numpy as np

def main():

    x = np.linspace(-np.pi, np.pi, 256, endpoint=True)  # 从 -pi到pi,有256个点
    c = np.cos(x)
    s = np.sin(x)
    plt.figure(1)

    # 第一个参数是自变量,第二个参数是因变量,线的颜色,线宽,线型,标签,透明度
    plt.plot(x, c, color="blue", linewidth=1.0, linestyle="-", label="cos", alpha=0.5)
    # r* 表示的是线型为*的红色线
    plt.plot(x, s, "r*", label="sin")
    plt.title("cos & sin")  # 加标题
    plt.show()

if __name__ == "__main__":
    main()
</
### 如何使用 Matplotlib绘制柱状图 以下是基于提供的引用内容以及专业知识所整理的内容,展示如何利用 `Matplotlib` 绘制柱状图。 #### 基础柱状图 基础柱状图是最简单的形式之一。可以通过 `plt.bar()` 函数实现。以下是一个基本的例子: ```python import matplotlib.pyplot as plt # 数据准备 categories = ['A', 'B', 'C', 'D'] values = [3, 7, 2, 5] # 创建柱状图 plt.bar(categories, values, color=['blue', 'green', 'red', 'purple']) # 设置标题和坐标轴标签 plt.title('Basic Bar Chart Example') plt.xlabel('Categories') plt.ylabel('Values') # 显示图像 plt.show() ``` 此代码片段展示了如何通过传递类别列表 (`categories`) 和对应的数值列表 (`values`) 来生成一个基础的柱状图[^3]。 --- #### 堆叠柱状图 当需要在同一分类上叠加多组数据时,可以使用堆叠柱状图。这通常用于比较同一类别下的子项差异。 ```python import numpy as np import matplotlib.pyplot as plt N = 4 menMeans = (20, 35, 30, 35) womenMeans = (25, 32, 34, 20) ind = np.arange(N) # x 轴的位置 width = 0.35 # 柱体宽度 p1 = plt.bar(ind, menMeans, width, label='Men') p2 = plt.bar(ind, womenMeans, width, bottom=menMeans, label='Women') plt.ylabel('Scores') plt.title('Stacked Bar Chart Scores by Group and Gender') plt.xticks(ind, ('G1', 'G2', 'G3', 'G4')) plt.yticks(np.arange(0, 81, 10)) plt.legend() plt.show() ``` 上述代码实现了两组数据(男性和女性得分)在一个图表中的堆叠显示[^4]。 --- #### 左右分布柱状图 如果想让两个对比的数据分别分布在中心两侧,则可调整条形的方向来完成这一目标。 ```python import matplotlib.pyplot as plt import numpy as np labels = ['Group A', 'Group B', 'Group C'] left_values = [10, 15, 30] right_values = [-25, -32, -34] x = np.arange(len(labels)) # 类别的位置 fig, ax = plt.subplots() bars_left = ax.bar(x - 0.2, left_values, 0.4, label='Left Data', align='center') bars_right = ax.bar(x + 0.2, right_values, 0.4, label='Right Data', align='center') ax.axhline(0, color='black', linewidth=0.8) # 添加水平基线 ax.set_ylabel('Values') ax.set_title('Symmetric Bar Chart with Positive/Negative Values') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() plt.show() ``` 这段代码演示了如何将正负值分列于零点两侧形成对称布局。 --- #### 带误差线的柱状图 为了表示每根柱的高度可能存在的不确定性范围,可以在柱顶加上误差棒。 ```python import matplotlib.pyplot as plt import numpy as np N = 5 means = (20, 35, 30, 35, 27) std_devs = (2, 3, 4, 1, 2) ind = np.arange(N) width = 0.6 fig, ax = plt.subplots() rects = ax.bar(ind, means, width, yerr=std_devs, capsize=5, color='SkyBlue', ecolor='Black') ax.set_ylabel('Scores') ax.set_title('Bar Chart with Error Bars') ax.set_xticks(ind) ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5')) def autolabel(rects): """Attach a text label above each bar.""" for rect in rects: height = rect.get_height() ax.annotate(f'{height}', xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom') autolabel(rects) plt.show() ``` 这里介绍了带有标准差作为误差指示器的方法[^1]。 --- #### 结合直方图与折线图 有时我们需要在同一个图表里既看到频率分布又观察趋势走向,这时可以用到组合型绘图技术。 ```python import matplotlib.pyplot as plt import numpy as np np.random.seed(19680801) data = np.random.randn(1000) fig, ax = plt.subplots() n, bins, patches = ax.hist(data, bins=50, density=True, alpha=0.75, edgecolor='w') # 计算并添加拟合曲线 mu, sigma = data.mean(), data.std() y = ((1 / (np.sqrt(2 * np.pi) * sigma)) * np.exp(-0.5 * (1 / sigma * (bins - mu))**2)) ax.plot(bins, y, '--r', linewidth=2) ax.set_xlabel('Value') ax.set_ylabel('Probability Density') ax.set_title(r'Histogram of IQ: $\mu={:.2f}$, $\sigma={:.2f}$'.format(mu, sigma)) plt.grid(True) plt.show() ``` 这个例子说明了怎样把直方统计结果同理论概率密度函数结合起来呈现出来[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值