How do I increase the opacity or alpha of the 'filled' area of my plot? I tried:
import pandas as pd
import plotly.offline as py
import plotly.graph_objs as go
import cufflinks as cf
from plotly import tools
plotly.offline.init_notebook_mode()
cf.go_offline()
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df.iplot(kind='area', fill=True, filename='cuflinks/stacked-area', opacity=.1)
but it doesn't seem to work.
There doesn't seem to be an easy built-in way of achieving this. However, a work-around is to first get the figure object of the plot, modify it to change the opacity, and then plot it.
You can get the figure object using the asFigure attribute like this:
figure = df.iplot(asFigure=True, kind='area', fill=True, filename='cuflinks/stacked-area')
The figure object in this case looks like:
Figure({
'data': [{'fill': 'tonexty',
'fillcolor': 'rgba(255, 153, 51, 0.3)',
'line': {'color': 'rgba(255, 153, 51, 1.0)', 'dash': 'solid', 'shape': 'linear', 'width': 1.3},
'mode': 'lines',
'name': 'a',
'text': '',
'type': 'scatter',
'uid': '4dcc1a3e-fba3-4a32-bb2a-40925b4fae5b',
'x': array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int64),
'y': array([0.91229144, 0.63049138, 0.22855077, 0.13470399, 0.9114691 , 0.39640368,
0.46534334, 0.20508211, 0.00203548, 0.41343938])},
{'fill': 'tonexty',
'fillcolor': 'rgba(55, 128, 191, 0.3)',
'line': {'color': 'rgba(55, 128, 191, 1.0)', 'dash': 'solid', 'shape': 'linear', 'width': 1.3},
'mode': 'lines',
'name': 'b',
'text': '',
'type': 'scatter',
'uid': '1015b30d-7c09-456c-875c-8a211a6ebdeb',
'x': array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int64),
'y': array([1.81115175, 1.57534372, 0.41288126, 0.38068805, 1.72268856, 0.87778503,
1.32714727, 0.848242 , 0.51605283, 0.58190402])},
{'fill': 'tonexty',
'fillcolor': 'rgba(50, 171, 96, 0.3)',
'line': {'color': 'rgba(50, 171, 96, 1.0)', 'dash': 'solid', 'shape': 'linear', 'width': 1.3},
'mode': 'lines',
'name': 'c',
'text': '',
'type': 'scatter',
'uid': '7d1852ac-b8e7-44e6-ae69-54229d7e2c83',
'x': array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int64),
'y': array([2.79222081, 1.58812634, 1.1439478 , 1.30453731, 2.50881795, 1.67681961,
1.85609861, 1.36657712, 0.89024486, 0.82749039])},
{'fill': 'tonexty',
'fillcolor': 'rgba(128, 0, 128, 0.3)',
'line': {'color': 'rgba(128, 0, 128, 1.0)', 'dash': 'solid', 'shape': 'linear', 'width': 1.3},
'mode': 'lines',
'name': 'd',
'text': '',
'type': 'scatter',
'uid': '89b85012-fc95-487c-b7ba-9cb6c249b768',
'x': array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int64),
'y': array([3.54740551, 1.79856232, 2.1326556 , 2.10560567, 2.64867039, 2.55519564,
2.73888819, 2.23274393, 1.16987343, 1.42794202])}],
'layout': {'legend': {'bgcolor': '#F5F6F9', 'font': {'color': '#4D5663'}},
'paper_bgcolor': '#F5F6F9',
'plot_bgcolor': '#F5F6F9',
'title': {'font': {'color': '#4D5663'}},
'xaxis': {'gridcolor': '#E1E5ED',
'showgrid': True,
'tickfont': {'color': '#4D5663'},
'title': {'font': {'color': '#4D5663'}, 'text': ''},
'zerolinecolor': '#E1E5ED'},
'yaxis': {'gridcolor': '#E1E5ED',
'showgrid': True,
'tickfont': {'color': '#4D5663'},
'title': {'font': {'color': '#4D5663'}, 'text': ''},
'zerolinecolor': '#E1E5ED'}}
})
You'll note that each trace in the data has a fillcolor attribute: 'fillcolor': 'rgba(255, 153, 51, 0.3)'. The last number is the alpha value, which you want to modify. I've made a hacky little function to update the fillcolor attribute of all traces in a figure object:
def update_opacity(figure,opacity):
for trace in range(len(figure['data'])):
# print(figure['data'][trace]['fillcolor'],'-> ',end='')
rgba_split = figure['data'][trace]['fillcolor'].split(',')
figure['data'][trace]['fillcolor'] = ','.join(rgba_split[:-1] + [' {})'.format(opacity)])
# print(figure['data'][trace]['fillcolor'])
return figure
For full opacity, you can do:
figure = update_opacity(figure,1)
Then, simply plot the result with
py.iplot(figure)
Output:
Related
I am trying to generate a chart with a secondary x-axis, but I can't get the secondary x-axis to be added to the chart.
Below is the code I'm using. If I change "x2_axis" to "y2_axis" and "set_x2_axis" to "set_y2_axis", then I am able to create a secondary y axis successfully -- but it does not work for a secondary x axis. Am I doing something wrong?
import xlsxwriter
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()
data = [
[1, 2, 3, 4, 5],
[10, 40, 50, 20, 10],
[1,1,2,2,3,3,4,4,5,5],
[200,200,100,100,300,300,250,250,350,350]
]
worksheet.write_column('A2', data[0])
worksheet.write_column('B2', data[1])
worksheet.write_column('C2', data[2])
worksheet.write_column('D2', data[3])
chart= workbook.add_chart({'type': 'line'})
chart.add_series ({
'name': 'Primary',
'categories': '=Sheet1!$A$2:$A$6',
'values': '=Sheet1!$B$2:$B$6',
})
chart.add_series ({
'name': 'Secondary',
'categories': '=Sheet1!$C$2:$C$11',
'values': '=Sheet1!$D$2:$D$11',
'x2_axis': True
})
chart.set_x_axis({
'name': 'Primary Axis',
'interval_unit': 1,
'interval_tick': 1,
'major_tick_mark': 'none',
})
chart.set_y_axis({
'name': 'Value',
})
chart.set_x2_axis({
'label_position': 'low',
'name': 'Secondary Axis',
'visible': True
})
worksheet.insert_chart('B20', chart)
workbook.close()
Setting a secondary X axis in Excel (or XlsxWriter) isn't obvious, in comparison to setting a secondary Y axis. Generally, you need to add a secondary Y and X axis pair before you can set a secondary X axis. Something like this:
import xlsxwriter
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()
data = [
[1, 2, 3, 4, 5],
[10, 40, 50, 20, 10],
[1, 1, 2, 2, 3, 3, 4, 4, 5, 5],
[200, 200, 100, 100, 300, 300, 250, 250, 350, 350]
]
worksheet.write_column('A2', data[0])
worksheet.write_column('B2', data[1])
worksheet.write_column('C2', data[2])
worksheet.write_column('D2', data[3])
chart = workbook.add_chart({'type': 'line'})
chart.add_series({
'name': 'Primary',
'categories': '=Sheet1!$A$2:$A$6',
'values': '=Sheet1!$B$2:$B$6',
})
chart.add_series({
'name': 'Secondary',
'categories': '=Sheet1!$C$2:$C$11',
'values': '=Sheet1!$D$2:$D$11',
'x2_axis': True,
'y2_axis': True,
})
chart.set_x_axis({
'name': 'Primary Axis',
'interval_unit': 1,
'interval_tick': 1,
'major_tick_mark': 'none',
})
chart.set_y_axis({
'name': 'Y Values 1',
})
chart.set_y2_axis({
'name': 'Y Values 2',
'crossing': 'max',
})
chart.set_x2_axis({
'label_position': 'high',
'name': 'Secondary Axis',
'visible': True,
})
worksheet.insert_chart('B20', chart)
workbook.close()
Output:
I'm creating a facet plot with plotly, which has two columns and a single row. I also have a list of dict for annotations, which looks like this...
annots = [{'x': datetime.datetime(2021, 5, 5, 14, 4, 47, 398000), 'y': 125.5, 'text': '8', 'font': {'color': 'black'}},
{'x': datetime.datetime(2021, 5, 5, 14, 4, 47, 545000), 'y': 123.5, 'text': '3', 'font': {'color': 'black'}},
{'x': datetime.datetime(2021, 5, 5, 14, 4, 47, 583000), 'y': 120.5, 'text': '9', 'font': {'color': 'black'}}]
I create layout dictionary and pass it to the figure object like this...
layout = dict(showlegend=False, height=HEIGHT, annotations=annots, barmode='overlay', hoverlabel=hoverlabel, legend=legend, margin=margin, xaxis=xaxes1, xaxis2=xaxes2, yaxis=yaxes1, yaxis2=yaxes2)
fig = go.Figure(data=data, layout=layout)
But all the annotations are displayed in the first column. How do I specify which annotations belong to which facet plot ?
It was very easy, I just need to specify xref and yref as keys in the dictionary. So it looks like this...
annots = [{'x': datetime.datetime(2021, 5, 5, 14, 4, 47, 398000), 'y': 125.5, 'text': '8', 'xref'='x2', 'font': {'color': 'black'}},
{'x': datetime.datetime(2021, 5, 5, 14, 4, 47, 545000), 'y': 123.5, 'text': '3', 'xref'='x2', 'font': {'color': 'black'}},
{'x': datetime.datetime(2021, 5, 5, 14, 4, 47, 583000), 'y': 120.5, 'text': '9', 'xref'='x', 'font': {'color': 'black'}}]
I have a list with barline ticks and midi notes that can overlap the barlines. So I made a list of 'barlineticks':
barlinepos = [0, 768.0, 1536.0, 2304.0, 3072.0, 3840.0, 4608.0, 5376.0, 6144.0, 6912.0, 0, 576.0, 1152.0, 1728.0, 2304.0, 2880.0, 3456.0, 4032.0, 4608.0, 5184.0, 5760.0, 6336.0, 6912.0, 7488.0]
And a MidiFile:
{'type': 'time_signature', 'numerator': 4, 'denominator': 4, 'time': 0, 'duration': 768, 'ID': 0}
{'type': 'set_tempo', 'tempo': 500000, 'time': 0, 'ID': 1}
{'type': 'track_name', 'name': 'Tempo Track', 'time': 0, 'ID': 2}
{'type': 'track_name', 'name': 'New Instrument', 'time': 0, 'ID': 3}
{'type': 'note_on', 'time': 0, 'channel': 0, 'note': 48, 'velocity': 100, 'ID': 4, 'duration': 956}
{'type': 'time_signature', 'numerator': 3, 'denominator': 4, 'time': 768, 'duration': 6911, 'ID': 5}
{'type': 'note_on', 'time': 768, 'channel': 0, 'note': 46, 'velocity': 100, 'ID': 6, 'duration': 575}
{'type': 'note_off', 'time': 956, 'channel': 0, 'note': 48, 'velocity': 0, 'ID': 7}
{'type': 'note_off', 'time': 1343, 'channel': 0, 'note': 46, 'velocity': 0, 'ID': 8}
{'type': 'end_of_track', 'time': 7679, 'ID': 9}
And I want to check if the midi note is overlapping a barline. Every note_on message has a 'time' and a 'duration' value. I have to check if one of the barlineticks(in the list) is inside the range of the note('time' and 'duration'). I tried:
if barlinepos in range(0, 956):
print(True)
Of course this doesn't work because barlinepos is a list. How can I check if one of the values in the list results in True?
Simple iteration to solve the requirement:
for i in midifile:
start, end = i["time"], i["time"]+i["duration"]
for j in barlinepos:
if j >= start and j<= end:
print(True)
break
print(False)
I created a bullet chart with a negative and positive dimension in plotly.go. However, when plotting my bar it always starts from -1. Is there a way to set the starting point at zero, so it can align in both dimensions from there?
Reproducable example:
act = 0.123
avg = 0.13
before = 0.15
fig = go.Figure(go.Indicator(
mode="number+gauge+delta", value=act,
domain={'x': [0.1, 1], 'y': [0, 1]},
title={'text': "<b>S-Score</b>"},
delta={'reference': before},
gauge={
'shape': "bullet",
'tick0':0,
'axis': {'range': [-1, 1]},
'threshold': {
'line': {'color': "white", 'width': 2},
'thickness': 0.75, 'value': avg},
'steps': [
{'range': [-1, 0], 'color': "#ff6666"},
{'range': [0, 1], 'color': "#89ac76"}
],
'bar': {'color': "grey"}}))
Actual Output:
Output I want:
I've done a lot of research and haven't found a solution. I propose a trick approach and a proposal to change the x-axis. This is a bit far from the answer you expect.
import plotly.graph_objects as go
act = 0.123
avg = 0.13
before = 0.15
fig = go.Figure(go.Indicator(
mode = "number+gauge+delta", value = act,
domain = {'x': [0.1, 1], 'y': [0, 1]},
title = {'text' :"<b>S-Score</b>"},
delta = {'reference': before},
gauge = {
'shape': "bullet",
'axis': {'range': [-1, 1]},
'threshold': {
'line': {'color': "white", 'width': 2},
'thickness': 0.75,
'value': avg},
'steps': [
{'range': [-1, 0], 'color': "#ff6666"},
{'range': [0, 1], 'color': "#89ac76"}],
'bar': {'color':'#ff6666'}
}))
fig.update_layout(height = 250)
fig.show()
import plotly.graph_objects as go
act = 0.123
avg = 0.13
before = 0.15
fig = go.Figure(go.Indicator(
mode = "number+gauge+delta", value = act,
domain = {'x': [0.1, 1], 'y': [0, 1]},
title = {'text' :"<b>S-Score</b>"},
delta = {'reference': before},
gauge = {
'shape': "bullet",
'axis': {'range': [0, 1]},
'threshold': {
'line': {'color': "white", 'width': 2},
'thickness': 0.75,
'value': avg},
'steps': [
{'range': [-1, 0], 'color': "#ff6666"},
{'range': [0, 1], 'color': "#89ac76"}],
'bar': {'color':'grey',
'line': {'color':'#444', 'width':2},
}}))
fig.update_layout(height = 250)
fig.show()
I've created complex query builder in my project, and during tests stumbled upon strange issue: same query with the same plan produces different results on different clients: cx_Oracle ignores order by clause, while Oracle SQLDeveloper Studio process query correctly, however in both cases order by present in both plans.
Query in question is:
select *
from
(
select
a.*,
ROWNUM tmp__rnum
from
(
select base.*
from
(
select id
from
(
(
select
profile_id as id,
surname as sort__col
from names
)
/* here usually are several other subqueries chained by unions */
)
group by id
order by min(sort__col) asc
) tmp
left join (profiles) base
on tmp.id = base.id
where exists
(
select t.object_id
from object_rights t
where
t.object_id = base.id
and t.subject_id = :a__subject_id
and t.rights in ('r','w')
)
) a
where ROWNUM < :rows_to
)
where tmp__rnum >= :rows_from
and plan from cx_Oracle in case I missed anything:
{'operation': 'SELECT STATEMENT', 'position': 9225, 'cardinality': 2164, 'time': 1, 'cost': 9225, 'depth': 0, 'bytes': 84396, 'optimizer': 'ALL_ROWS', 'id': 0, 'cpu_cost': 1983805801},
{'operation': 'VIEW', 'position': 1, 'filter_predicates': '"TMP__RNUM">=TO_NUMBER(:ROWS_FROM)', 'parent_id': 0, 'object_instance': 1, 'cardinality': 2164SEL$1', 'projection': '"from$_subquery$_001"."ID"[NUMBER,22], "from$_subquery$_001"."CREATION_TIME"[TIMESTAMP,11], "TMP__RNUM"[NUMBER,22]', 'time': 1, 'cost': 9225, 'depth': 1, 'bytes': 84396, 'id': 1, 'cpu_cost': 1983805801},
{'operation': 'COUNT', 'position': 1, 'filter_predicates': 'ROWNUM<TO_NUMBER(:ROWS_TO)', 'parent_id': 1, 'projection': '"BASE"."ID"[NUMBER,22], "BASE"."CREATION_TIME"[TIMESTAMP,11], ROWNUM[8]', 'options': 'STOPKEY', 'depth': 2, 'id': 2,
{'operation': 'HASH JOIN', 'position': 1, 'parent_id': 2, 'access_predicates': '"TMP"."ID"="BASE"."ID"', 'cardinality': 2164, 'projection': '(#keys=1) "BASE"."ID"[NUMBER,22], "BASE"."CREATION_TIME"[TIMESTAMP,11]', 'time': 1, 'cost': 9225, 'depth': 3, 'bytes': 86560, 'id': 3, 'cpu_cost': 1983805801},
{'operation': 'JOIN FILTER', 'position': 1, 'parent_id': 3, 'object_owner': 'SYS', 'cardinality': 2219, 'projection': '"BASE"."ID"[NUMBER,22], "BASE"."CREATION_TIME"[TIMESTAMP,11]', 'object_name': ':BF0000', 'time': 1, 'cost': 662, 'options': 'CREATE', 'depth': 4, 'bytes': 59913, 'id': 4, 'cpu_cost': 223290732},
{'operation': 'HASH JOIN', 'position': 1, 'parent_id': 4, 'access_predicates': '"T"."OBJECT_ID"="BASE"."ID"', 'cardinality': 2219, 'projection': '(#keys=1) "BASE"."ID"[NUMBER,22], "BASE"."CREATION_TIME"[TIMESTAMP,11]', 'time': 1, 'cost': 662, 'options': 'RIGHT SEMI', 'depth': 5, 'bytes': 59913, 'id': 5, 'cpu_cost': 223290732},
{'operation': 'TABLE ACCESS', 'position': 1, 'filter_predicates': '"T"."SUBJECT_ID"=TO_NUMBER(:A__SUBJECT_ID) AND ("T"."RIGHTS"=\'r\' OR "T"."RIGHTS"=\'w\')', 'parent_id': 5, 'object_type': 'TABLE', 'object_instance': 8, 'cardinality': 2219, 'projection': '"T"."OBJECT_ID"[NUMBER,22]', 'object_name': 'OBJECT_RIGHTS', 'time': 1, 'cost': 5, 'options': 'FULL', 'depth': 6, 'bytes': 24409, 'optimizer': 'ANALYZED', 'id': 6, 'cpu_cost': 1823386},
{'operation': 'TABLE ACCESS', 'position': 2, 'parent_id': 5, 'object_type': 'TABLE', 'object_instance': 6, 'cardinality': 753862, 'projection': '"BASE"."ID"[NUMBER,22], "BASE"."CREATION_TIME"[TIMESTAMP,11]', 'object_name': 'PROFILES', 'time': 1, 'cost': 654, 'options': 'FULL', 'depth': 6, 'bytes': 12061792, 'optimizer': 'ANALYZED', 'id': 7, 'cpu_cost': 145148296},
{'operation': 'VIEW', 'position': 2, 'parent_id': 3, 'object_instance': 3, 'cardinality': 735296, 'projection': '"TMP"."ID"[NUMBER,22]', 'time': 1, 'cost': 8559, 'depth': 4, 'bytes': 9558848, 'id': 8, 'cpu_cost': 1686052619},
{'operation': 'SORT', 'position': 1, 'parent_id': 8, 'cardinality': 735296, 'projection': '(#keys=1) MIN("SURNAME")[50], "PROFILE_ID"[NUMBER,22]', 'time': 1, 'cost': 8559, 'options': 'ORDER BY', 'temp_space': 18244000, 'depth': 5, 'bytes': 10294144, 'id': 9, 'cpu_cost': 1686052619},
{'operation': 'HASH', 'position': 1, 'parent_id': 9, 'cardinality': 735296, 'projection': '(#keys=1; rowset=200) "PROFILE_ID"[NUMBER,22], MIN("SURNAME")[50]', 'time': 1, 'cost': 8559, 'options': 'GROUP BY', 'temp_space': 18244000, 'depth': 6, 'bytes': 10294144, 'id': 10, 'cpu_cost': 1686052619},
{'operation': 'JOIN FILTER', 'position': 1, 'parent_id': 10, 'object_owner': 'SYS', 'cardinality': 756586, 'projection': '(rowset=200) "PROFILE_ID"[NUMBER,22], "SURNAME"[VARCHAR2,50]', 'object_name': ':BF0000', 'time': 1, 'cost': 1202, 'options': 'USE', 'depth': 7, 'bytes': 10592204, 'id': 11, 'cpu_cost': 190231639},
{'operation': 'TABLE ACCESS', 'position': 1, 'filter_predicates': 'SYS_OP_BLOOM_FILTER(:BF0000,"PROFILE_ID")', 'parent_id': 11, 'object_type': 'TABLE', 'object_instance': 5, 'cardinality': 756586, 'projection': '(rowset=200) "PROFILE_ID"[NUMBER,22], "SURNAME"[VARCHAR2,50]', 'object_name': 'NAMES', 'time': 1, 'cost': 1202, 'options': 'FULL', 'depth': 8, 'bytes': 10592204, 'optimizer': 'ANALYZED', 'id': 12, 'cpu_cost': 190231639}
cx_Oracle output (appears to be ordered by id):
ID, Created, rownum
(1829, 2016-08-24, 1)
(2438, 2016-08-24, 2)
SQLDeveloper Output (ordered by surname, as expected):
ID, Created, rownum
(518926, 2016-08-28, 1)
(565556, 2016-08-29, 2)
I don't see an ORDER BY clause that would affect the ordering of the results of the query. In SQL, the only way to guarantee the ordering of a result set is to have an ORDER BY clause for the outer-most SELECT.
In almost all cases, an ORDER BY in a subquery is not necessarily respected (Oracle makes an exception when there are rownum comparisons in the next level of the query -- and even that is now out of date with the support of FETCH FIRST <n> ROWS).
So, there is no reason to expect that an ORDER BY in the innermost subquery would have any effect, particularly with the JOIN that then happens.
Suggestions:
Move the ORDER BY to the outermost query.
Use FETCH FIRST syntax, if you are using Oracle 12c+.
Move the ORDER BY after the JOIN.
Use ROW_NUMBER() instead of rownum.