本文整理汇总了Python中matplotlib.colors.is_color_like函数的典型用法代码示例。如果您正苦于以下问题:Python is_color_like函数的具体用法?Python is_color_like怎么用?Python is_color_like使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了is_color_like函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: validate_color
def validate_color(s):
"return a valid color arg"
try:
if s.lower() == "none":
return "None"
except AttributeError:
pass
if is_color_like(s):
return s
stmp = "#" + s
if is_color_like(stmp):
return stmp
# If it is still valid, it must be a tuple.
colorarg = s
msg = ""
if s.find(",") >= 0:
# get rid of grouping symbols
stmp = "".join([c for c in s if c.isdigit() or c == "." or c == ","])
vals = stmp.split(",")
if len(vals) != 3:
msg = "\nColor tuples must be length 3"
else:
try:
colorarg = [float(val) for val in vals]
except ValueError:
msg = "\nCould not convert all entries to floats"
if not msg and is_color_like(colorarg):
return colorarg
raise ValueError("%s does not look like a color arg%s" % (s, msg))
开发者ID:zaherabdulazeez,项目名称:matplotlib,代码行数:32,代码来源:rcsetup.py
示例2: validate_color
def validate_color(s):
'return a valid color arg'
try:
if s.lower() == 'none':
return 'None'
except AttributeError:
pass
if is_color_like(s):
return s
stmp = '#' + s
if is_color_like(stmp):
return stmp
# If it is still valid, it must be a tuple.
colorarg = s
msg = ''
if s.find(',') >= 0:
# get rid of grouping symbols
stmp = ''.join([c for c in s if c.isdigit() or c == '.' or c == ','])
vals = stmp.split(',')
if len(vals) != 3:
msg = '\nColor tuples must be length 3'
else:
try:
colorarg = [float(val) for val in vals]
except ValueError:
msg = '\nCould not convert all entries to floats'
if not msg and is_color_like(colorarg):
return colorarg
raise ValueError('%s does not look like a color arg%s' % (s, msg))
开发者ID:olgabot,项目名称:matplotlib,代码行数:31,代码来源:rcsetup.py
示例3: get
def get(self):
valuelist = []
for index, (label, value) in enumerate(self.data):
field = self.widgets[index]
if label is None:
# Separator / Comment
continue
elif tuple_to_qfont(value) is not None:
value = field.get_font()
elif (isinstance(value, six.string_types)
or mcolors.is_color_like(value)):
value = six.text_type(field.text())
elif isinstance(value, (list, tuple)):
index = int(field.currentIndex())
if isinstance(value[0], (list, tuple)):
value = value[index][0]
else:
value = value[index]
elif isinstance(value, bool):
value = field.checkState() == QtCore.Qt.Checked
elif isinstance(value, float):
value = float(str(field.text()))
elif isinstance(value, int):
value = int(field.value())
elif isinstance(value, datetime.datetime):
value = field.dateTime().toPyDateTime()
elif isinstance(value, datetime.date):
value = field.date().toPyDate()
else:
value = eval(str(field.text()))
valuelist.append(value)
return valuelist
开发者ID:AlexandreAbraham,项目名称:matplotlib,代码行数:32,代码来源:formlayout.py
示例4: WaitingtimesDistributions
def WaitingtimesDistributions(self,waiting_times,rates,trajectory_index,linestyle,linewidth, marker,colors,title,xlabel,ylabel,is_legend,legend_location):
"""
Plots the waiting times for each reaction in the model.
Makes use of ObtainWaitingtimes to derive the waiting times out of the SSA output.
Input:
- *waiting_times* (dict)
- *rates* (list)
- *trajectory_index* (integer)
- *linestyle* (string)
- *linewith* (float)
- *marker* (string)
- *colors* (list)
- *title* (string)
- *xlabel* (string)
- *ylabel* (string)
- *is_legend* (boolean)
- *legend_location* [default = 'upper right'] (string/integer)
"""
plt.figure(self.plotnum)
if len(rates) == 1:
j = trajectory_index
else:
j=0
L_legend_names = []
for r_id in rates:
L_waiting_times = waiting_times[r_id] # get list of waiting times for a given reaction
if len(L_waiting_times) > 1: # At least 2 waiting times are necessary per reaction
(x,y,nbins) = LogBin(L_waiting_times,1.5) # Create logarithmic bins (HARDCODED 1.5)
if x != None:
if colors == None:
if j >= len(self.colors):
j=0
elif isinstance(colors,list):
if j >= len(colors):
j=0
elif isinstance(colors,str):
colors = [colors]
j=0
if colors == None:
plt.loglog(x,y,marker,ls = linestyle,lw=linewidth,color = self.colors[j])
else:
if clr.is_color_like(colors[j]):
plt.loglog(x,y,marker,ls = linestyle,lw=linewidth,color = colors[j])
else:
print("*** WARNING ***: '{0}' is not recognized as a valid color code".format(colors[j]) )
plt.loglog(x,y,marker,ls = linestyle,lw=linewidth,color = self.colors[j])
colors = None
L_legend_names.append(r_id)
j+=1
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
if is_legend:
plt.legend(L_legend_names,numpoints=1,frameon=True,loc=legend_location)
开发者ID:SystemsBioinformatics,项目名称:stochpy,代码行数:57,代码来源:Analysis.py
示例5: draw_merge_contour
def draw_merge_contour(self, color, idx=0):
if is_color_like(color):
color = hex2color(color)
color = np.array(color)
color = np.round(color*np.iinfo(self.dtype).max)
ix, iy, _ = self.contours[idx]
# shift contour from subimage to the last column
xoff = (self._nsub-1-idx)*self.swidth
self[ix+xoff, iy] = color
开发者ID:bobi5rova,项目名称:cecog,代码行数:10,代码来源:images.py
示例6: TimeSeries
def TimeSeries(self,data,npoints,datatype,labels,trajectory_index,linestyle,linewidth,marker,colors,title,xlabel,ylabel,is_legend,legend_location):
"""
Tracks the propensities and/or species over time.
Input:
- *data* (array)
- *npoints* (integer)
- *datatype* (list)
- *labels* (list)
- *trajectory_index* (integer)
- *linestyle* (string)
- *linewidth* (float)
- *title* (string)
- *xlabel* (string)
- *ylabel* (string)
- *is_legend* (boolean)
"""
plt.figure(self.plotnum)
datatype_indices = [labels.index(Id) for Id in datatype]
data = getDataForTimeSimPlot(data,npoints,self.quiet)
Arr_time = data[:,0]
if len(datatype) == 1:
j = trajectory_index
else:
j=0
for i in datatype_indices:
y = data[:,i+1]
if colors == None:
if j >= len(self.colors):
j=0
elif isinstance(colors,list):
if j >= len(colors):
j=0
elif isinstance(colors,str):
colors = [colors]
j=0
if colors == None:
plt.plot(Arr_time,y,marker,ls = linestyle,lw = linewidth,color = self.colors[j])
else:
if clr.is_color_like(colors[j]):
plt.plot(Arr_time,y,marker,ls = linestyle,lw = linewidth,color = colors[j])
else:
print("*** WARNING ***: '{0}' is not recognized as a valid color code".format(colors[j]) )
plt.plot(Arr_time,y,marker,ls = linestyle,lw = linewidth,color = self.colors[j])
colors = None
j+=1
if is_legend:
plt.legend(datatype,numpoints=1,frameon=True,loc=legend_location)
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
开发者ID:SystemsBioinformatics,项目名称:stochpy,代码行数:55,代码来源:Analysis.py
示例7: AverageTimeSeries
def AverageTimeSeries(self,means,stds,time,nstd,datatype,labels,linestyle,linewidth,marker,ms,colors,title,xlabel,ylabel,is_legend,legend_location):
"""
Plots the average and standard deviation of datatype on a regular grid.
Input:
- *means* (array)
- *stds* (array)
- *time* (array)
- *nstd* (float)
- *datatype* (list)
- *labels* (list)
- *linestyle* (string)
- *linewidth* (float)
- *marker* (string)
- *ms* (float)
- *colors* (list)
- *title* (string)
- *xlabel* (string)
- *ylabel* (string)
- *is_legend* (boolean)
- *legend_location* [default = 'upper right'] (string/integer)
"""
assert nstd > 0, "Error: The number of STDs must be a value larger than zero"
plt.figure(self.plotnum)
datatype_indices = [labels.index(Id) for Id in datatype]
j=0
for i in datatype_indices:
if colors == None:
if j >= len(self.colors):
j=0
elif isinstance(colors,list):
if j >= len(colors):
j=0
elif isinstance(colors,str):
colors = [colors]
j=0
# plot with y-axis error bars
if colors == None:
plt.errorbar(time,means[:,i],yerr = nstd*np.array(stds[:,i]),color = self.colors[j],ls = linestyle,lw=linewidth,marker = marker,ms=ms,label = labels[i])
else:
if clr.is_color_like(colors[j]):
plt.errorbar(time,means[:,i],yerr = nstd*np.array(stds[:,i]),color = colors[j],ls = linestyle,lw=linewidth,marker = marker,ms=ms,label = labels[i])
else:
print("*** WARNING ***: '{0}' is not recognized as a valid color code".format(colors[j]) )
plt.errorbar(time,means[:,i],yerr = nstd*np.array(stds[:,i]),color = self.colors[j],ls = linestyle,lw=linewidth,marker = marker,ms=ms,label = labels[i])
colors = None
j+=1
if is_legend:
plt.legend(numpoints=1,frameon=True,loc=legend_location)
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
开发者ID:SystemsBioinformatics,项目名称:stochpy,代码行数:53,代码来源:Analysis.py
示例8: Autocorrelations
def Autocorrelations(self,lags,data,datatype,labels,trajectory_index,linestyle,linewidth,marker,colors,title,xlabel,ylabel,is_legend,legend_location):
"""
Input:
- *lags*
- *data* (array)
- *datatype* (list)
- *labels* (list)
- *trajectory_index* (integer)
- *linestyle* (string)
- *linewidth* (float)
- *marker* string)
- *colors* (list)
- *title* (string)
- *xlabel* (string)
- *ylabel* (string)
- *is_legend* (boolean)
"""
plt.figure(self.plotnum)
datatype_indices = [labels.index(Id) for Id in datatype]
if len(datatype) == 1:
j = trajectory_index
else:
j=0
for i in datatype_indices:
if colors == None:
if j >= len(self.colors):
j=0
elif isinstance(colors,list):
if j >= len(colors):
j=0
elif isinstance(colors,str):
colors = [colors]
j=0
y = data[i][0:len(lags)]
if colors == None:
plt.plot(lags,y,marker,ls = linestyle,lw = linewidth, color = self.colors[j])
else:
if clr.is_color_like(colors[j]):
plt.plot(lags,y,marker,ls = linestyle,lw = linewidth, color = colors[j])
else:
print("*** WARNING ***: '{0}' is not recognized as a valid color code".format(colors[j]) )
plt.plot(lags,y,marker,ls = linestyle,lw = linewidth, color = self.colors[j])
colors = None
j+=1
if is_legend:
plt.legend(datatype,numpoints=1,frameon=True,loc=legend_location)
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
开发者ID:SystemsBioinformatics,项目名称:stochpy,代码行数:51,代码来源:Analysis.py
示例9: add_contour
def add_contour(self, position, contour, color):
if is_color_like(color):
color = hex2color(color)
if color is None:
color = hex2color(Colors.white)
color = np.array(color)
color = np.round(color*np.iinfo(self.dtype).max)
# filter pixels that do not lie in the sub image
contour = np.array(filter(
lambda c: c[0]<self.swidth and c[1]<self.swidth, contour))
contour = contour + np.array((position*self.swidth, 0))
# rgb color according to dtype of the image
self.contours.append((contour[:, 0], contour[:, 1], color))
开发者ID:bobi5rova,项目名称:cecog,代码行数:16,代码来源:images.py
示例10: AverageDistributionsCI
def AverageDistributionsCI(self,means,stds,nstd,datatype,labels,colors,title,xlabel,ylabel,is_legend,legend_location):
"""
Plots the average and standard deviation.
Input:
- *means* (nested list)
- *stds* (nested list)
- *nstd* (float)
- *labels* (list)
- *linestyle* (string)
- *linewidth* (float)
- *marker* (string)
- *colors* (list)
- *title* (string)
- *xlabel* (string)
- *ylabel* (string)
- *is_legend* (boolean)
- *legend_location* [default = 'upper right'] (string/integer)
"""
assert nstd > 0, "Error: The number of STDs must be a value larger than zero"
plt.figure(self.plotnum)
datatype_indices = [labels.index(Id) for Id in datatype]
for i in datatype_indices:
L_s_amount = copy.copy(means[i][0])
L_mu = copy.copy(means[i][1])
L_sigma = copy.copy(stds[i][1])
# Add an additional value
L_s_amount.append(L_s_amount[-1]+1)
L_mu.append(L_mu[-1])
L_sigma.append(L_sigma[-1])
X_i = []
Y_i = []
L_errors = []
for j in range(len(L_s_amount)):
if (not L_s_amount[j] == L_s_amount[0]) and (not L_s_amount[j] == L_s_amount[-1]):
X_i.append(L_s_amount[j])
Y_i.append(L_mu[j-1])
L_errors.append(L_sigma[j-1])
X_i.append(L_s_amount[j])
Y_i.append(L_mu[j])
L_errors.append(L_sigma[j])
X_e = np.concatenate([X_i, X_i[::-1]])
Y_e = np.concatenate([np.array(Y_i) - nstd*np.array(L_errors) ,(np.array(Y_i) + nstd*np.array(L_errors))[::-1]])
if colors == None:
if j >= len(self.colors):
j=0
elif isinstance(colors,list):
if j >= len(colors):
j=0
elif isinstance(colors,str):
colors = [colors]
j=0
if colors == None:
plt.fill(X_e-0.5,Y_e, alpha=.25, ec='None', label='{0} STD confidence interval'.format(nstd),color = self.colors[j])
plt.plot(np.array(X_i)-0.5,np.array(Y_i),color = self.colors[j])
else:
if clr.is_color_like(colors[j]):
plt.fill(X_e-0.5,Y_e, alpha=.25, ec='None', label='{0} STD confidence interval'.format(nstd),color = colors[j])
plt.plot(np.array(X_i)-0.5,np.array(Y_i),color = colors[j])
else:
print("*** WARNING ***: '{0}' is not recognized as a valid color code".format(colors[j]) )
plt.fill(X_e-0.5,Y_e, alpha=.25, ec='None', label='{0} STD confidence interval'.format(nstd),color = self.colors[j])
plt.plot(np.array(X_i)-0.5,np.array(Y_i),color = self.colors[j])
colors = None
if is_legend:
plt.legend(numpoints=1,frameon=True,loc=legend_location)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
开发者ID:SystemsBioinformatics,项目名称:stochpy,代码行数:72,代码来源:Analysis.py
示例11: grey2rgb
def grey2rgb(image, color="#FFFFFF"):
if is_color_like(color):
color = hex2color(color)
# be aware that color contains floats ranging from 0 to 1
return np.dstack((image, image, image))*np.array(color)
开发者ID:bobi5rova,项目名称:cecog,代码行数:5,代码来源:images.py
示例12: setup
def setup(self):
for label, value in self.data:
if DEBUG:
print("value:", value)
if label is None and value is None:
# Separator: (None, None)
self.formlayout.addRow(QtGui.QLabel(" "), QtGui.QLabel(" "))
self.widgets.append(None)
continue
elif label is None:
# Comment
self.formlayout.addRow(QtGui.QLabel(value))
self.widgets.append(None)
continue
elif tuple_to_qfont(value) is not None:
field = FontLayout(value, self)
elif is_color_like(value):
field = ColorLayout(to_qcolor(value), self)
elif isinstance(value, (str, unicode)):
field = QtGui.QLineEdit(value, self)
elif isinstance(value, (list, tuple)):
if isinstance(value, tuple):
value = list(value)
selindex = value.pop(0)
field = QtGui.QComboBox(self)
if isinstance(value[0], (list, tuple)):
keys = [ key for key, _val in value ]
value = [ val for _key, val in value ]
else:
keys = value
field.addItems(value)
if selindex in value:
selindex = value.index(selindex)
elif selindex in keys:
selindex = keys.index(selindex)
elif not isinstance(selindex, int):
print("Warning: '%s' index is invalid (label: " \
"%s, value: %s)" % (selindex, label, value), file=STDERR)
selindex = 0
field.setCurrentIndex(selindex)
elif isinstance(value, bool):
field = QtGui.QCheckBox(self)
if value:
field.setCheckState(QtCore.Qt.Checked)
else :
field.setCheckState(QtCore.Qt.Unchecked)
elif isinstance(value, float):
field = QtGui.QLineEdit(repr(value), self)
field.setValidator(QtGui.QDoubleValidator(field))
dialog = self.get_dialog()
dialog.register_float_field(field)
self.connect(field, QtCore.SIGNAL('textChanged(QString)'),
lambda text: dialog.update_buttons())
elif isinstance(value, int):
field = QtGui.QSpinBox(self)
field.setRange(-1e9, 1e9)
field.setValue(value)
elif isinstance(value, datetime.datetime):
field = QtGui.QDateTimeEdit(self)
field.setDateTime(value)
elif isinstance(value, datetime.date):
field = QtGui.QDateEdit(self)
field.setDate(value)
else:
field = QtGui.QLineEdit(repr(value), self)
self.formlayout.addRow(label, field)
self.widgets.append(field)
开发者ID:agoodm,项目名称:matplotlib,代码行数:67,代码来源:formlayout.py
示例13: float
"""
======================
Link to other packages
======================
Use :mod:`sphinx_gallery` to link to other packages, like
:mod:`numpy`, :mod:`matplotlib.colors`, and :mod:`matplotlib.pyplot`.
FYI this gallery uses :obj:`sphinx_gallery.sorting.FileNameSortKey`.
"""
import numpy as np
from matplotlib.colors import is_color_like
import matplotlib
import matplotlib.pyplot as plt
from local_module import N # N = 1000
t = np.arange(N) / float(N)
win = np.hanning(N)
print(is_color_like('r'))
plt.figure()
plt.plot(t, win, color='r')
plt.text(0, 1, 'png', size=40, va='top')
orig_dpi = 80. if matplotlib.__version__[0] < '2' else 100.
assert plt.rcParams['figure.dpi'] == orig_dpi
plt.rcParams['figure.dpi'] = 70.
assert plt.rcParams['figure.dpi'] == 70.
开发者ID:sphinx-gallery,项目名称:sphinx-gallery,代码行数:28,代码来源:plot_numpy_matplotlib.py
示例14: setup
def setup(self):
for label, value in self.data:
if label is None and value is None:
# Separator: (None, None)
self.formlayout.addRow(QtWidgets.QLabel(" "), QtWidgets.QLabel(" "))
self.widgets.append(None)
continue
elif label is None:
# Comment
self.formlayout.addRow(QtWidgets.QLabel(value))
self.widgets.append(None)
continue
elif tuple_to_qfont(value) is not None:
field = FontLayout(value, self)
elif (label.lower() not in BLACKLIST
and mcolors.is_color_like(value)):
field = ColorLayout(to_qcolor(value), self)
elif isinstance(value, str):
field = QtWidgets.QLineEdit(value, self)
elif isinstance(value, (list, tuple)):
if isinstance(value, tuple):
value = list(value)
# Note: get() below checks the type of value[0] in self.data so
# it is essential that value gets modified in-place.
# This means that the code is actually broken in the case where
# value is a tuple, but fortunately we always pass a list...
selindex = value.pop(0)
field = QtWidgets.QComboBox(self)
if isinstance(value[0], (list, tuple)):
keys = [key for key, _val in value]
value = [val for _key, val in value]
else:
keys = value
field.addItems(value)
if selindex in value:
selindex = value.index(selindex)
elif selindex in keys:
selindex = keys.index(selindex)
elif not isinstance(selindex, Integral):
warnings.warn(
"index '%s' is invalid (label: %s, value: %s)" %
(selindex, label, value), stacklevel=2)
selindex = 0
field.setCurrentIndex(selindex)
elif isinstance(value, bool):
field = QtWidgets.QCheckBox(self)
if value:
field.setCheckState(QtCore.Qt.Checked)
else:
field.setCheckState(QtCore.Qt.Unchecked)
elif isinstance(value, Integral):
field = QtWidgets.QSpinBox(self)
field.setRange(-1e9, 1e9)
field.setValue(value)
elif isinstance(value, Real):
field = QtWidgets.QLineEdit(repr(value), self)
field.setCursorPosition(0)
field.setValidator(QtGui.QDoubleValidator(field))
field.validator().setLocale(QtCore.QLocale("C"))
dialog = self.get_dialog()
dialog.register_float_field(field)
field.textChanged.connect(lambda text: dialog.update_buttons())
elif isinstance(value, datetime.datetime):
field = QtWidgets.QDateTimeEdit(self)
field.setDateTime(value)
elif isinstance(value, datetime.date):
field = QtWidgets.QDateEdit(self)
field.setDate(value)
else:
field = QtWidgets.QLineEdit(repr(value), self)
self.formlayout.addRow(label, field)
self.widgets.append(field)
开发者ID:dopplershift,项目名称:matplotlib,代码行数:72,代码来源:formlayout.py
示例15: plot_segmentlist
def plot_segmentlist(self, segmentlist, y=None, height=.8, label=None,
collection=True, rasterized=None, **kwargs):
"""Plot a `~gwpy.segments.SegmentList` onto these axes
Parameters
----------
segmentlist : `~gwpy.segments.SegmentList`
list of segments to display
y : `float`, optional
y-axis value for new segments
collection : `bool`, default: `True`
add all patches as a
`~matplotlib.collections.PatchCollection`, doesn't seem
to work for hatched rectangles
label : `str`, optional
custom descriptive name to print as y-axis tick label
**kwargs
any other keyword arguments acceptable for
`~matplotlib.patches.Rectangle`
Returns
-------
collection : `~matplotlib.patches.PatchCollection`
list of `~matplotlib.patches.Rectangle` patches
"""
# get colour
facecolor = kwargs.pop('facecolor', kwargs.pop('color', '#629fca'))
if is_color_like(facecolor):
kwargs.setdefault('edgecolor', tint(facecolor, factor=.5))
# get y
if y is None:
y = self.get_next_y()
# build patches
patches = [SegmentRectangle(seg, y, height=height, facecolor=facecolor,
**kwargs) for seg in segmentlist]
if collection: # map to PatchCollection
coll = PatchCollection(patches, match_original=patches,
zorder=kwargs.get('zorder', 1))
coll.set_rasterized(rasterized)
coll._ignore = collection == 'ignore'
coll._ypos = y
out = self.add_collection(coll)
# reset label with tex-formatting now
# matplotlib default label is applied by add_collection
# so we can only replace the leading underscore after
# this point
if label is None:
label = coll.get_label()
coll.set_label(to_string(label))
else:
out = []
for patch in patches:
patch.set_label(label)
patch.set_rasterized(rasterized)
label = ''
out.append(self.add_patch(patch))
self.autoscale(enable=None, axis='both', tight=False)
return out
开发者ID:diegobersanetti,项目名称:gwpy,代码行数:65,代码来源:segments.py
示例16: _plot_kmf_single
def _plot_kmf_single(df,
condition_col,
survival_col,
censor_col,
threshold,
title,
xlabel,
ylabel,
ax,
with_condition_color,
no_condition_color,
with_condition_label,
no_condition_label,
color_map,
label_map,
color_palette,
ci_show,
print_as_title):
"""
Helper function to produce a single KM survival plot, among observations in df by groups defined by condition_col.
All inputs are required - this function is intended to be called by `plot_kmf`.
"""
# make color inputs consistent hex format
if colors.is_color_like(with_condition_color):
with_condition_color = colors.to_hex(with_condition_color)
if colors.is_color_like(no_condition_color):
no_condition_color = colors.to_hex(no_condition_color)
## prepare data to be plotted; producing 3 outputs:
# - `condition`, series containing category labels to be plotted
# - `label_map` (mapping condition values to plot labels)
# - `color_map` (mapping condition values to plotted colors)
if threshold is not None:
is_median = threshold == "median"
if is_median:
threshold = df[condition_col].median()
label_suffix = float_str(threshold)
condition = df[condition_col] > threshold
default_label_no_condition = "%s ≤ %s" % (condition_col, label_suffix)
if is_median:
label_suffix += " (median)"
default_label_with_condition = "%s > %s" % (condition_col, label_suffix)
with_condition_label = with_condition_label or default_label_with_condition
no_condition_label = no_condition_label or default_label_no_condition
if not label_map:
label_map = {False: no_condition_label,
True: with_condition_label}
if not color_map:
color_map = {False: no_condition_color,
True: with_condition_color}
elif df[condition_col].dtype == 'O' or df[condition_col].dtype.name == "category":
condition = df[condition_col].astype("category")
if not label_map:
label_map = dict()
[label_map.update({condition_value: '{} = {}'.format(condition_col,
condition_value)})
for condition_value in condition.unique()]
if not color_map:
rgb_values = sb.color_palette(color_palette, len(label_map.keys()))
hex_values = [colors.to_hex(col) for col in rgb_values]
color_map = dict(zip(label_map.keys(), hex_values))
elif df[condition_col].dtype == 'bool':
condition = df[condition_col]
default_label_with_condition = "= {}".format(condition_col)
default_label_no_condition = "¬ {}".format(condition_col)
with_condition_label = with_condition_label or default_label_with_condition
no_condition_label = no_condition_label or default_label_no_condition
if not label_map:
label_map = {False: no_condition_label,
True: with_condition_label}
if not color_map:
color_map = {False: no_condition_color,
True: with_condition_color}
else:
raise ValueError('Don\'t know how to plot data of type\
{}'.format(df[condition_col].dtype))
# produce kmf plot for each category (group) identified above
kmf = KaplanMeierFitter()
grp_desc = list()
grp_survival_data = dict()
grp_event_data = dict()
grp_names = list(condition.unique())
for grp_name, grp_df in df.groupby(condition):
grp_survival = grp_df[survival_col]
grp_event = (grp_df[censor_col].astype(bool))
grp_label = label_map[grp_name]
grp_color = color_map[grp_name]
kmf.fit(grp_survival, grp_event, label=grp_label)
desc_str = "# {}: {}".format(grp_label, len(grp_survival))
grp_desc.append(desc_str)
grp_survival_data[grp_name] = grp_survival
grp_event_data[grp_name] = grp_event
if ax:
ax = kmf.plot(ax=ax, show_censors=True, ci_show=ci_show, color=grp_color)
else:
ax = kmf.plot(show_censors=True, ci_show=ci_show, color=grp_color)
## format the plot
# Set the y-axis to range 0 to 1
#.........这里部分代码省略.........
开发者ID:hammerlab,项目名称:cohorts,代码行数:101,代码来源:survival.py
示例17: Distributions
def Distributions(self,distributions,datatype,labels,trajectory_index,linestyle,linewidth,colors,title,xlabel,ylabel,is_legend=True,legend_location='upper right',bin_size=1,histtype = 'step',orientation='vertical',multiplotting=False):
"""
Plots the distributions of species and/or propensities
Normed=False because the total probability is determined by summation not by integration.
Input:
- *distributions* (nested list)
- *datatype* (list)
- *labels* (list)
- *trajectory_index* (integer)
- *linestyle* (string)
- *linewidth* (float)
- *colors* (list)
- *title* (string)
- *xlabel* (string)
- *ylabel* (string)
- *is_legend* (boolean)
- *legend_location* [default = 'upper right'] (string/integer)
- *bin_size* (string) [default = 1]
- *histtype* (string)) [default = 'step']
- *orientation* (string) [default = 'vertical']
- *multiplotting* (boolean) [default = False]
"""
plt.figure(self.plotnum)
datatype_indices = [labels.index(Id) for Id in datatype]
if len(datatype) == 1:
j = trajectory_index
else:
j=0
for i in datatype_indices:
dat_min = distributions[i][0].min()
dat_max = distributions[i][0].max()
n_bins = 1 + (dat_max-dat_min) /bin_size # Just take one trajectory as reference
L_bin_edges = np.linspace(dat_min-bin_size/2.0,dat_max+bin_size/2.0,n_bins+1)
if colors == None:
if j >= len(self.colors):
j=0
elif isinstance(colors,list):
if j >= len(colors):
j=0
elif isinstance(colors,str):
colors = [colors]
j=0
if colors == None:
output = plt.hist(distributions[i][0],L_bin_edges,weights = distributions[i][1],ls = linestyle,lw = linewidth,color = self.colors[j],histtype = histtype,orientation=orientation,normed=False)
else:
if clr.is_color_like(colors[j]):
output = plt.hist(distributions[i][0],L_bin_edges,weights = distributions[i][1],ls = linestyle,lw = linewidth,color = colors[j],histtype = histtype,orientation=orientation,normed=False)
else:
print("*** WARNING ***: '{0}' is not recognized as a valid color code".format(colors[j]) )
output = plt.hist(distributions[i][0],L_bin_edges,weights = distributions[i][1],ls = linestyle,lw = linewidth,color = self.colors[j],histtype = histtype,orientation=orientation,normed=False)
colors = None
j+=1
if is_legend:
plt.legend(datatype,numpoints=1,frameon=True,loc=legend_location)
plt.title(title)
if orientation.lower() == 'horizontal':
plt.xlabel(ylabel)
plt.ylabel(xlabel)
if multiplotting:
plt.xticks([0,max(output[0])*1.1])
else:
plt.xlabel(xlabel)
plt.ylabel(ylabel)
if multiplotting:
plt.yticks([0,max(output[0])*1.1])
开发者ID:SystemsBioinformatics,项目名称:stochpy,代码行数:70,代码来源:Analysis.py
示例18: setup
def setup(self):
for label, value in self.data:
if DEBUG:
print("value:", value)
if label is None and value is None:
# Separator: (None, None)
self.formlayout.addRow(QtWidgets.QLabel(" "), QtWidgets.QLabel(" "))
self.widgets.append(None)
continue
elif label is None:
# Comment
self.formlayout.addRow(QtWidgets.QLabel(value))
self.widgets.append(None)
continue
elif tuple_to_qfont(value) is not None:
field = FontLayout(value, self)
elif (label.lower() not in BLACKLIST
and mcolors.is_color_like(value)):
field = ColorLayout(to_qcolor(value), self)
elif isinstance(value, six.string_types):
field = QtWidgets.QLineEdit(value, self)
elif isinstance(value, (list, tuple)):
if isinstance(value, tuple):
value = list(value)
selindex = value.pop(0)
field = QtWidgets.QComboBox(self)
if isinstance(value[0], (list, tuple)):
keys = [key for key, _val in value]
value = [val for _key, val in value]
else:
keys = value
field.addItems(value)
if selindex in value:
selindex = value.index(selindex)
elif selindex in keys:
selindex = keys.index(selindex)
elif not isinstance(selindex, int):
warnings.warn(
"index '%s' is invalid (label: %s, value: %s)" %
(selindex, label, value))
selindex = 0
field.setCurrentIndex(selindex)
elif isinstance(value, bool):
field = QtWidgets.QCheckBox(self)
if value:
field.setCheckState(QtCore.Qt.Checked)
else:
field.setCheckState(QtCore.Qt.Unchecked)
elif isinstance(value, float):
field = QtWidgets.QLineEdit(repr(value), self)
field.setCursorPosition(0)
field.setValidator(QtGui.QDoubleValidator(field))
field.validator().setLocale(QtCore.QLocale("C"))
dialog = self.get_dialog()
dialog.register_float_field(field)
field.textChanged.connect(lambda text: dialog.update_buttons())
elif isinstance(value, int):
field = QtWidgets.QSpinBox(self)
field.setRange(-1e9, 1e9)
field.setValue(value)
elif isinstance(value, datetime.datetime):
field = QtWidgets.QDateTimeEdit(self)
field.setDateTime(value)
elif isinstance(value, datetime.date):
field = QtWidgets.QDateEdit(self)
field.setDate(value)
else:
field = QtWidgets.QLineEdit(repr(value), self)
self.formlayout.addRow(label, field)
self.widgets.append(field)
开发者ID:AlexandreAbraham,项目名称:matplotlib,代码行数:70,代码来源:formlayout.py
示例19: plot_profile
def plot_profile(self):
if not self.color_list:
cmap_plot = plt.get_cmap('jet')
|
请发表评论