简体   繁体   中英

Matplotlib Logscale colorbar with for loop for loading data and plotting?

I am trying to load data from multiple text files that contains two columns at least. The two first columns are plotted in regular 2D plot, but the color of each line is mapped to a third variable, " c " is the code below.

In my best attempt the colorbar ticks are compressed because ' c ' is in logscale. and I don't know how to increment the color value in the loop. Also, there is some rendering issue where the lines have some sort of aliasing caused by the loop, as seen in the attached image.

I am also interested in solutions using pandas.

Thanks in advance !

import numpy as np
import matplotlib.pyplot as plt
import os
import matplotlib as mpl

myfiles = [myfile for myfile in os.listdir() if myfile.endswith(".txt")]

c = np.logspace(3,7,10, endpoint=True)

norm = mpl.colors.Normalize(vmin=c.min(), vmax=c.max())
cmap = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.Reds)
cmap.set_array([])

for myfile in myfiles:
    x, y = np.loadtxt(myfile, delimiter='\t', unpack=True)
    for i in range(len(c)):
        plt.plot(x,y, c=cmap.to_rgba(i+1))

plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
plt.xlabel('$V_{D}$  ($V$)', fontsize=14)
plt.ylabel('$C_{gg}$ ($F$)', fontsize=14)
plt.tick_params(axis='both', labelsize='12')
plt.grid(True, which="both", ls="-")
plt.colorbar(cmap, ticks=c)

plt.show()

figure

I fixed the colorbar scale using the code below. But the I still didn't figure out how to properly color the lines:

import numpy as np
import matplotlib.pyplot as plt
import os
import matplotlib as mpl
myfiles = [myfile for myfile in os.listdir() if myfile.endswith(".txt")]

c = np.logspace(3,7,10, endpoint=True)

fig, ax = plt.subplots()
cmap = mpl.cm.get_cmap('Reds', 10)

dummie_cax = ax.scatter(c, c, c=c, cmap=cmap,norm=mpl.colors.LogNorm())
ax.cla()

for myfile in myfiles:
    x, y = np.loadtxt(myfile, delimiter='\t', unpack=True)
    for i,yi in enumerate(y.T):
        plt.plot(x,y,c=cmap(i))

plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
plt.xlabel('$V_{D}$  ($V$)', fontsize=14)
plt.ylabel('$C_{gg}$ ($F$)', fontsize=14)
plt.tick_params(axis='both', labelsize='12')
plt.grid(True, which="both", ls="-")
cbar = plt.colorbar(dummie_cax, ticks=c)
cbar.set_ticks([1.00000000e+03, 2.78255940e+03, 7.74263683e+03, 2.15443469e+04,
       5.99484250e+04, 1.66810054e+05, 4.64158883e+05, 1.29154967e+06,
       3.59381366e+06, 1.00000000e+07])
cbar.set_ticklabels(["1e+03", "2.7e+03", "7.7e+03", "2.1e+04",
       "5.9e+04", "1.6e+05", "4.6e+05", "1.2e+06",
       "3.5e+06", "1e+07"])

cbar.ax.locator_params(nbins=10)

plt.show()

Result: 图2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM