Search code examples
pandascsvmatplotlibpolar-plot

matplotlib polar plot with multiple colored lines


I have 3 data columns in a .csv that I would like to produce 2 different lines in a polar plot. Each line will be based on the "Attenuation [dB]" column.

Here is my csv file:

Step Index, Position [Deg], Attenuation [dB], Traffic Pair 1 Throughput [Mbps]
0, 0, 10, 955.940
1, 15, 10, 955.786
2, 30, 10, 955.773
3, 45, 10, 955.476
4, 60, 10, 955.600
5, 75, 10, 956.005
6, 90, 10, 955.959
7, 105, 10, 955.855
8, 120, 10, 955.443
9, 135, 10, 955.664
10, 150, 10, 955.235
11, 165, 10, 955.590
12, 180, 10, 954.828
13, 195, 10, 955.947
14, 210, 10, 955.752
15, 225, 10, 955.573
16, 240, 10, 956.017
17, 255, 10, 955.767
18, 270, 10, 955.999
19, 285, 10, 955.941
20, 300, 10, 955.943
21, 315, 10, 955.474
22, 330, 10, 955.883
23, 345, 10, 955.971
24, 0, 20, 955.969
25, 15, 20, 955.421
26, 30, 20, 955.443
27, 45, 20, 956.016
28, 60, 20, 955.887
29, 75, 20, 955.939
30, 90, 20, 955.919
31, 105, 20, 955.986
32, 120, 20, 956.015
33, 135, 20, 955.927
34, 150, 20, 956.041
35, 165, 20, 955.467
36, 180, 20, 955.985
37, 195, 20, 955.926
38, 210, 20, 955.964
39, 225, 20, 953.396
40, 240, 20, 955.215
41, 255, 20, 955.380
42, 270, 20, 954.877
43, 285, 20, 955.992
44, 300, 20, 955.996
45, 315, 20, 956.002
46, 330, 20, 955.914
47, 345, 20, 955.755
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
subPlot = fig.add_subplot(projection = "polar")

columns = ['Position [Deg]', 'Traffic Pair 1 Throughput [Mbps]', 'Attenuation [dB]']
df = pd.read_csv("polarPlotTest.csv", usecols=columns, delimiter=', ')
df['Position [Deg]'] = np.deg2rad(df['Position [Deg]'])

subPlot.plot(df['Position [Deg]'], df['Traffic Pair 1 Throughput [Mbps]'])
plt.show()

This code currently only produces one full connected line. How do I add my "Attenuation [dB]" variable in as a separate line/subplot?


Solution

  • If you don't have that many groups then you can simply loop through them using groupby.

    import pandas as pd
    from matplotlib import pyplot as plt
    import numpy as np
    
    fig, ax = plt.subplots(subplot_kw={"projection":"polar"})
    
    # I reformatted the csv so there aren't any spaces
    df = pd.read_csv("data.csv")
    df["Position [Deg]"] = np.deg2rad(df["Position [Deg]"])
    
    for group, data in df.groupby("Attenuation [dB]"):
        ax.plot(data["Position [Deg]"], data["Traffic Pair 1 Throughput [Mbps]"], label=group)
    ax.set_ylim(df["Traffic Pair 1 Throughput [Mbps]"].min(), 
                df["Traffic Pair 1 Throughput [Mbps]"].max())
    ax.legend()